I'm trying to figure out how to import text files (always named tracks.txt) from different folders into one workbook with separate worksheets named after the folder.
basically it should work like this:
select main folder
select multiple sub-folders (which contain the tracks.txt)
or
search in all sub-folders starting with the string (user input)
import tracks.txt in new worksheet
replace worksheetname with subfoldername
would this be possible?
'//-----------------------------------------------------------------------------------------\\
'||code was made with the great help of bsalv and especially snb from www.worksheet.nl ||
'||adjusted and supplemented for original question by myself martijndg (www.worksheet.nl) ||
'\\-----------------------------------------------------------------------------------------//
Function GetFolder(strPath As String) As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select folder with subfolder (containing tracks.txt) NO SPACES IN FILEPATH!!!"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1) + "\" 'laatste slash toegevoegd aan adres
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Sub importtracks()
Dim subfolder, serie As String
c00 = GetFolder("C:\")
serie = InputBox(Prompt:="partial foldername of serie", _
Title:="find folders of 1 serie", Default:="track##.")
If serie = "track##." Or serie = vbNullString Then
Exit Sub
End If
Workbooks.Add
For Each it In Filter(Split(CreateObject("wscript.shell").exec("cmd /c Dir " & c00 & "tracks.txt /b /s").stdout.readall, vbCrLf), ":")
sn = Split(CreateObject("scripting.filesystemobject").opentextfile(it).readall, vbCrLf)
With Sheets
subfolder = Replace(Replace(CreateObject("scripting.filesystemobject").GetParentFolderName(it), "" & c00 & "", ""), "\", "")
End With
If InStr(1, subfolder, serie, vbTextCompare) Then
With Sheets.Add
.Move after:=Sheets(Sheets.Count)
.name = subfolder
.Cells(1).Resize(UBound(sn) + 1) = WorksheetFunction.Transpose(sn)
.Columns(1).TextToColumns , xlDelimited, semicolon:=True
End With
End If
Next
If Sheets.Count = 3 And Sheets(Sheets.Count).name = "Sheet3" Then
MsgBox "no subfolder contained the string '" & serie & "' or your choosen filepath contained spaces"
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
Exit Sub
End If
Application.DisplayAlerts = False
Sheets("Sheet1").Delete
Sheets("Sheet2").Delete
Sheets("Sheet3").Delete
Application.DisplayAlerts = True
End Sub
Related
I'm trying figure out how to modify the code I came across (can be found below). So instead of it making the worksheets as pages to pdf, I would want it to make them as individual pdf files. It should ass well avoid certain list of names for example:
"pricing",
"cover" and
"important",
and it should take the name from the sheet it's making the pdf from. I'm at a dead end right now, so might as well ask.
Here's to code (This code selects the file the Excels are in, makes you choose where the pdf files go to and loops trough every worksheet in the folder (For instance i got 50 files with 3 sheets each and I need each sheet as their own pdf:s to be an attachment for an invoice)):
Sub ExcelSaveAsPDF()
Dim strPath As String
Dim xStrFile1, xStrFile2 As String
Dim xWbk As Workbook
Dim xSFD, xRFD As FileDialog
Dim xSPath As String
Dim xRPath, xWBName As String
Dim xBol As Boolean
Set xSFD = Application.FileDialog(msoFileDialogFolderPicker)
With xSFD
.Title = "Please select the folder contains the Excel files you want to "
convert:"
.InitialFileName = "C:\"
End With
If xSFD.Show <> -1 Then Exit Sub
xSPath = xSFD.SelectedItems.Item(1)
Set xRFD = Application.FileDialog(msoFileDialogFolderPicker)
With xRFD
.Title = "Please select a destination folder to save the converted files:"
.InitialFileName = "C:\"
End With
If xRFD.Show <> -1 Then Exit Sub
xRPath = xRFD.SelectedItems.Item(1) & "\"
strPath = xSPath & "\"
xStrFile1 = Dir(strPath & "*.*")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While xStrFile1 <> ""
xBol = False
If Right(xStrFile1, 3) = "xls" Then
Set xWbk = Workbooks.Open(Filename:=strPath & xStrFile1)
xbwname = Replace(xStrFile1, ".xls", "_pdf")
xBol = True
ElseIf Right(xStrFile1, 4) = "xlsx" Then
Set xWbk = Workbooks.Open(Filename:=strPath & xStrFile1)
xbwname = Replace(xStrFile1, ".xlsx", "_pdf")
xBol = True
ElseIf Right(xStrFile1, 4) = "xlsm" Then
Set xWbk = Workbooks.Open(Filename:=strPath & xStrFile1)
xbwname = Replace(xStrFile1, ".xlsm", "_pdf")
xBol = True
End If
If xBol Then
xWbk.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xRPath & xbwname & ".pdf"
xWbk.Close SaveChanges:=False
End If
xStrFile1 = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Credits to U/Jimm_kirkk for helping with this project.
My original reddit Post: [Here][1]!
Code explanation:
Makes you select the folder that contains the Excel files and where the pdf files go to.
After that it makes every sheet ad individual pdf.
In the code is a place you can set a list of names to avoid printing as pdf.
Takes around a minute per 10 excel files.
The code:
Sub ExcelSaveAsPDF()
Dim strPath As String
Dim xStrFile1, xStrFile2 As String
Dim xWbk As Workbook
Dim xSFD, xRFD As FileDialog
Dim xSPath As String
Dim xRPath, xWBName As String
Dim xBol As Boolean
Set xSFD = Application.FileDialog(msoFileDialogFolderPicker)
With xSFD
.Title = "Please select the folder contains the Excel files you want to convert:"
.InitialFileName = "C:\"
End With
If xSFD.Show <> -1 Then Exit Sub
xSPath = xSFD.SelectedItems.Item(1)
Set xRFD = Application.FileDialog(msoFileDialogFolderPicker)
With xRFD
.Title = "Please select a destination folder to save the converted files:"
.InitialFileName = "C:\"
End With
If xRFD.Show <> -1 Then Exit Sub
xRPath = xRFD.SelectedItems.Item(1) & "\"
strPath = xSPath & "\"
xStrFile1 = Dir(strPath & "*.*")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While xStrFile1 <> ""
xBol = False
If Right(xStrFile1, 3) = "xls" Then
Set xWbk = Workbooks.Open(Filename:=strPath & xStrFile1)
'modified xbwname to be simplified name
xbwname = Replace(xStrFile1, ".xls", "")
xBol = True
ElseIf Right(xStrFile1, 4) = "xlsx" Then
Set xWbk = Workbooks.Open(Filename:=strPath & xStrFile1)
'modified xbwname to be simplified name
xbwname = Replace(xStrFile1, ".xlsx", "")
xBol = True
ElseIf Right(xStrFile1, 4) = "xlsm" Then
Set xWbk = Workbooks.Open(Filename:=strPath & xStrFile1)
'modified xbwname to be simplified name
xbwname = Replace(xStrFile1, ".xlsm", "")
xBol = True
End If
If xBol Then
'modified here to install sub main_ExportPDF()
Sheet_ExportPDF xWbk, xRPath & xbwname
''''''''''''''''''''''''''''''''''''''''''''''
xWbk.Close SaveChanges:=False
End If
xStrFile1 = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Sub Sheet_ExportPDF(wb As Workbook, fname As String)
'Purpose: determine sheets to be exported to pdf
'store base workbook name
Dim baseWB As String
baseWB = fname
'user to define what names to avoid by adding to string
Const NTA As String = "pricing,cover,important"
'build array of names to avoid
Dim NamesToAvoid As Variant
NamesToAvoid = Split(NTA, ",")
'process visible worksheets and compare to NamesToAvoid, export the
'sheets that are not in conflict with user's list to avoid
Dim ws As Worksheet, blnConflict As Boolean, i As Long
For Each ws In wb.Worksheets
'determine if sheet is visible
If ws.Visible = xlSheetVisible Then
'loop through user's list to avoid
For i = LBound(NamesToAvoid) To UBound(NamesToAvoid)
'if on the avoidance list, set bln and exit loop
If UCase(ws.Name) = Trim(UCase(NamesToAvoid(i))) Then
blnConflict = True
Exit For
End If
Next i
'process appropriate safe sheets
fname = baseWB & "_" & ws.Name & ".pdf"
If Not blnConflict Then ExportPDF ws, fname Else blnConflict = False
End If
Next ws
End Sub
Function ExportPDF(sht As Worksheet, fname As String)
'Purpose: facilitate exporting to pdf
'execute the exporting with some basic parameters set to user's needs
sht.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fname, quality:=xlQualityStandard, _
includedocproperties:=True, ignoreprintareas:=True, openafterpublish:=False
End Function
good luck!
I am trying to loop through all the 'xlsx' files in a folder and convert them to 'xls' ( Excel 97-2003 Worksheet) format. I use the following codes but then the output files are still saved as 'xlsx' instead of 'xls'. I am a beginner and looking to learn more from others. Thanks for your help!
Sub Convert()
Dim strPath As String
Dim strFile As String
Dim strfilenew As String
Dim xWbk As Workbook
Dim xSFD, xRFD As FileDialog
Dim xSPath As String
Dim xRPath As String
Set xSFD = Application.FileDialog(msoFileDialogFolderPicker)
With xSFD
.Title = "Please select the folder contains the xls files:"
.InitialFileName = "C:\"
End With
If xSFD.Show <> -1 Then Exit Sub
xSPath = xSFD.SelectedItems.Item(1)
Set xRFD = Application.FileDialog(msoFileDialogFolderPicker)
With xRFD
.Title = "Please select a folder for outputting the new files:"
.InitialFileName = "C:\"
End With
If xRFD.Show <> -1 Then Exit Sub
xRPath = xRFD.SelectedItems.Item(1) & "\"
strPath = xSPath & "\"
strFile = Dir(strPath & "*.xlsx")
strfilenew = Dir(strPath & "*.xls")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While strFile <> ""
If Right(strFile, 4) = "xlsx" Then
Set xWbk = Workbooks.Open(Filename:=strPath & strfilenew)
xWbk.SaveAs Filename:=xRPath & strfilenew, _
FileFormat:=xlExcel18
xWbk.Close SaveChanges:=True
End If
strFile = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
There was a bit of a mix-up in your file naming, basically as evidenced by the several double-declarations that I removed. The really big mistake was here, Set xWbk = Workbooks.Open(Filename:=strPath & strfilenew) where you tried to open the old workbook by the new name. I think the confusion started here "Please select the folder contains the xls files:". Of course, this is the folder with the XLSX files. The recommended antidote is to use "meaningful" variable names but you chose to speak in riddles (like xSFD) which makes coding more difficult.
However, the code below is largely yours, and it does work.
Sub Convert()
' 230
Dim Spath As String ' path to read from (XLSX files)
Dim Rpath As String ' path to write to (XLS files)
Dim strFile As String ' loop variable: current file name
Dim Wbk As Workbook ' loop object: current workbook(strFile)
Dim Sp() As String ' split array of strFile
Dim strFileNew As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select the folder contains the XLSX files:"
.InitialFileName = "C:\"
If .Show <> -1 Then Exit Sub
Spath = .SelectedItems.Item(1) & "\"
End With
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder for outputting the new files:"
.InitialFileName = "C:\"
If .Show <> -1 Then Exit Sub
Rpath = .SelectedItems.Item(1) & "\"
End With
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
strFile = Dir(Spath & "*.xlsx")
Do While strFile <> ""
If Right(strFile, 4) = "xlsx" Then
Sp = Split(strFile, ".")
Sp(UBound(Sp)) = "xls"
strFileNew = Join(Sp, ".")
Set Wbk = Workbooks.Open(Filename:=Spath & strFile)
Wbk.SaveAs Filename:=Rpath & strFileNew, FileFormat:=xlExcel8
Wbk.Close SaveChanges:=True
End If
strFile = Dir
Loop
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub
Observe that the new file name is created by splitting the old name on periods, changing the last element, and reassembling the modified array.
I am having 2 issues with the below code.
on the first loop it finds the same file, hence why I have it skip if the file is the same name. After that it will proceed as it should. On the 3rd loop instead of finding the 3rd file (fileName2 = Dir) becomes fileName2 = "".
When I want fileName to go to the second file (fileName = Dir) I get a run time 5 error.
*Note: I currently have 6 files in the folder that I am testing but I will want to use for folders that have 10,000 small files
Sub TestMD5()
Dim myfilepath As String
Dim myfilepath2 As String
Dim fileName As Variant
Dim fileName2 As Variant
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem & "\"
Set fldr = Nothing
fileName = Dir(GetFolder)
fileName2 = Dir(GetFolder)
Do While fileName <> ""
Do While fileName2 <> ""
myfilepath = GetFolder & fileName
myfilepath2 = GetFolder & fileName2
If myfilepath <> myfilepath2 Then
If FileToMD5Hex(myfilepath) = FileToMD5Hex2(myfilepath2) And FileToSHA1Hex(myfilepath) =
FileToSHA1Hex2(myfilepath2) Then
'Kill (myfilepath2)
Debug.Print "match - " & (fileName) & " & " & (fileName2)
Else
Debug.Print "no match - " & (fileName) & " & " & (fileName2)
End If
End If
fileName2 = Dir
Loop
'Set the fileName to the next file
fileName = Dir
Loop
End Sub
I mashed your code together with the "File system Object" approach, where we can do a For each loop on the files.
This at least gets you away from the whole run time 5 error. Maybe it could be of use.
Sub TestMD5()
Dim myfilepath As Variant, myfilepath2 As Variant
Dim sItem As String
Dim fso As Object
Dim fldr As Variant
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.GetFolder(sItem & "\")
For Each myfilepath In fldr.Files
For Each myfilepath2 In fldr.Files
If Not myfilepath = myfilepath2 Then
If FileToMD5Hex(myfilepath) = FileToMD5Hex2(myfilepath2) And FileToSHA1Hex(myfilepath) = FileToSHA1Hex2(myfilepath2) Then
'Kill (myfilepath2)
Debug.Print "match - " & (myfilepath) & " & " & (myfilepath2)
Else
Debug.Print "no match - " & (myfilepath) & " & " & (myfilepath2)
End If
End If
Next myfilepath2
Next myfilepath
End Sub
I think FileDialog(msoFileDialogFilePicker) should be used instead of FileDialog(msoFileDialogFolderPicker)
Hi I have drafted the below code, which use the DIR function to loop through all the files and rename them, however this is not carried out in alphabetical order
Can the below code be amended to ensure it is completed in alphabetical order.
Sub Rename_Files()
Dim name As String
Dim returnaname As String
returnName = ActiveWorkbook.name
Application.ScreenUpdating = True
Application.DisplayAlerts = False
Application.EnableEvents = False
'On Error Resume Next
MyFolder = "G:\Corpdata\STRAT_Information\Open\1. Yot Data (Scoring)\34. Disproportionality Tool\201718 Tool\Local Level Tool\Database_Extract_Tools\Area Files Offences"
MyFile = Dir(MyFolder & "\*.xls")
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile
name = Left(ActiveWorkbook.name, Len(ActiveWorkbook.name) - 5)
name = name & ("_Offence")
ActiveWorkbook.SaveAs Filename:=name
Windows(returnName).Activate
MyFile = Dir$ 'goes to next entry
Loop
End Sub
How do I programmatically change the file name of a .txt using excel vba, I need a script where it will go through a folder which consists of txt files and remove time from its filename.
Original Filename: ABC_ABCDE_ABCD_YYYYMMDDTTTTTT.txt
New Filename: ABC_ABCDE_ABCD_YYYYMMDD.txt
Thank you in advance
Mike
As per My understanding of your question, I write a code which asks a user to select the folder and rename ".txt" file as per requirements, you may be add an additional code of line for perfect work
'call sub LoopThroughFiles
'this sub is loop every file and rename it
Sub LoopThroughFiles()
Dim txtfile As String, folderPath As String
Dim newName As String
folderPath = GetFolder()
txtfile = Dir(folderPath & "\" & "*.txt")
While txtfile <> ""
If checkFormat(txtfile) = True Then
newName = Left(txtfile, 23) & ".txt"
On Error Resume Next
'rename file is done here
If Not txtfile = "" Then Name (folderPath + "\" + txtfile) As (folderPath + "\" + newName)
On Error GoTo 0
End If
txtfile = Dir
Wend
End Sub
'this function is for check format of file
'you may edit it as per your requirment
Function checkFormat(str As String) As Boolean
checkFormat = False
If Len(str) = 33 And Mid(str, 4, 1) = "_" Then
checkFormat = True
End If
End Function
'this function for select folder path
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Before use this code please make an additional copy of your file in case some error you have a backup...
Hope This help