How to loop through two different paths in VBA? [duplicate] - excel

I have the code below that I would like to run to all of the available excel files in a folder. Ideally, I would like to input the path of the folder into cell C3 in Sheet1 and the macro to apply the code to all of the existing files.
The code will simply save the second sheet of each file into a PDF version, it works perfectly standalone.
Sample Folder Path:
C:\Users\MMMM\Desktop\Project X\ Project II
Suggestions on how to approach this?
Private Sub CommandButton1_Click()
Dim MyFolder As String, MyFile As String
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
MyFolder = .SelectedItems(1)
Err.Clear
End With
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
MyFile = Dir(MyFolder & "\", vbReadOnly)
Do While MyFile <> ""
DoEvents
On Error GoTo 0
Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False
Dim ReportSheet As Worksheet
Dim allColumns As Range
Set allColumns = Sheets("RT").Columns("N:S")
allColumns.Hidden = True
With Worksheets("RT").PageSetup
.Zoom = False
.FitToPagesWide = 1
End With
Filename = ActiveWorkbook.Name
Cell = Replace(Filename, ".xlsx", ".PDF")
Set ReportSheet = Sheets("RT")
Sheets("RT").Select
Sheets("RT").PageSetup.Orientation = xlLandscape
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & "\" & Cell, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=True, OpenAfterPublish:=True
0
Workbooks(MyFile).Close SaveChanges:=False
MyFile = Dir
Loop
'turns settings back on that you turned off before looping folders
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
Application.Calculation = xlCalculationManual
End Sub

This needs a reference (see this link)
It's untested (so let me know if anything comes up)
Basically:
As suggested by SmileyFtW it asks you for the root folder
Scans the subfolders for excel files (adjust the extension in code)
Process the DoSomething procedure where you export the file
EDIT: Added handle user cancel file select dialog
Code:
Option Explicit
' Add a reference to Microsoft Scripting Runtime
' See https://vbaf1.com/filesystemobject/create-microsoft-scripting-runtime-library-reference/
Private Sub ProcessAllFilesInFolder()
Dim FileSystem As Scripting.FileSystemObject
Dim fileDialogResult As Office.FileDialog
Dim folderPath As String
Set FileSystem = New Scripting.FileSystemObject
Set fileDialogResult = Application.FileDialog(msoFileDialogFolderPicker)
With fileDialogResult
.AllowMultiSelect = False
.Title = "Select a folder"
If .Show = True Then
folderPath = .SelectedItems(1)
End If
If .SelectedItems.Count = 0 Then Exit Sub
End With
ProcessFolder FileSystem.GetFolder(folderPath)
End Sub
Private Sub ProcessFolder(ByVal targetFolder As Scripting.Folder)
Dim FileSystem As Scripting.FileSystemObject
Dim File As Scripting.File
Dim SubFolder As Scripting.Folder
Set FileSystem = New Scripting.FileSystemObject
For Each SubFolder In targetFolder.SubFolders
ProcessFolder SubFolder
Next
For Each File In targetFolder.Files
If FileSystem.GetExtensionName(File.Name) Like "xls?" And File.Name <> ThisWorkbook.Name Then
DoSomething File.Path
End If
Next
End Sub
Private Sub DoSomething(ByVal filePath As String)
Dim FileSystem As Scripting.FileSystemObject
Dim ReportSheet As Worksheet
Dim targetFileName As String
targetFileName = Replace(ThisWorkbook.Name, ".xlsm", ".PDF")
Set ReportSheet = ThisWorkbook.Worksheets("Sheet2")
ReportSheet.PageSetup.Orientation = xlLandscape
ReportSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & "\" & targetFileName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=True, OpenAfterPublish:=True
End Sub
Let me know if it works!

Related

Loop through files and find and replace columns

I have a VBA script below that loops through files in a folder. I would like to find and replce any "$" with "" (nothing) in columns I and J.
When I run this script it appears to run, but there are no changes within the files. Not too sure where the issue is. Any help would be appreciated.
Thanks!
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Find and replace col I and J
wb.Worksheets(1).Range("I:J").Replace What:="$", Replacement:=""
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
*Edit - I have found it will work with .xlsx files, but not with .csv. I would need it to work with csv, so any suggestions would be great.
Try something like this:
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String, ext
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show = -1 Then myPath = .SelectedItems(1)
End With
If myPath <> "" Then
myPath = myPath & "\"
For Each ext In Array("*.xls*", "*.csv") 'loop different extension patterns
myFile = Dir(myPath & ext)
Do While myFile <> ""
'Debug.Print myFile
Set wb = Workbooks.Open(Filename:=myPath & myFile)
wb.Worksheets(1).Range("I:J").Replace _
What:="$", Replacement:="", LookAt:=xlPart
wb.Close SaveChanges:=True
myFile = Dir()
Loop
Next ext
End If
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Note - where possible you should avoid use of Goto for flow control. You only really need Goto for handling runtime errors (or maybe for breaking out of nested loops).

Looping through excel files in a folder and performing a procedure on each of them VBA

My Aim:
This procedure is meant to loop through excel files in a specified folder and preform a sub (cleanDataAndTransfer), which is meant to clean the data in the files being looped through and then paste it in to a new sheet in the master file.
My problem:
Im getting the Run-time error '91': Object variable or With block variable not set on the .Title = "Select A Target Folder" line.
I've tried different solutions to rectify the issue but nothing has yet worked.
My code:
Sub loopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
myExtension = "*.xls*"
myFile = Dir(myPath & myExtension)
Do While myFile <> ""
Set wb = Workbooks.Open(FileName:=myPath & myFile)
DoEvents
Call cleanDataAndTransfer
wb.Close SaveChanges:=True
DoEvents
myFile = Dir
Loop
ResetSettings:
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
I would really appreciate any suggestions on how to solve this bug and any other improvements! Thanks in advance :)
I don't have a Mac to test this but you could try an InputBox.
update - no filter on Dir
Sub loopAllExcelFilesInFolder()
Sub loopAllExcelFilesInFolder2()
Const EXT = "csv"
Dim wb As Workbook, myPath As String, myFile As String
Dim count As Integer, isWindows As Boolean
myPath = ThisWorkbook.Path & Application.PathSeparator
myPath = VBA.InputBox("Enter folder", "Folder", myPath)
If myPath = "" Then Exit Sub
If Right(myPath, 1) <> Application.PathSeparator Then
myPath = myPath & Application.PathSeparator
End If
myFile = Dir(myPath)
Do While myFile <> ""
If Right(myFile, Len(EXT)) = EXT Then
Set wb = Workbooks.Open(Filename:=myPath & myFile)
Call cleanDataAndTransfer
wb.Close SaveChanges:=True
count = count + 1
End If
myFile = Dir
Loop
MsgBox count & " files cleaned", vbInformation
End Sub

Why does loop stop after exporting only one file?

I am trying to export Excel files to another folder as PDFs. The macro is stored in a separate .xlsm that I have open, and I directed the code to the folder with all the files that need to be PDFs.
The code only exports the first PDF in the folder. The error I got was that it could not operate in Page Break Mode, so I set it to normal mode for running the code but I still get the error.
Beyond that, it is reading the workbook that I have the macro stored in as a second active window. I ran the code to export to PDF on a single PDF and it worked as expected.
Option Explicit
Sub PPG_PDF_File()
'Below is used to make code run faster
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim wkbDest As Workbook
Dim wkbSource As Workbook
Set wkbDest = ThisWorkbook
Dim strExtension As String
Dim wsA As Worksheet
Dim strName As String
Dim strName1 As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Const strPath1 As String = "C:\Users\steve.argen\Documents\PPG\GW Sampling March 2020\PPG Balogna NUMBER 2\Final excel sheets\Test Macro Folder DNAPL Wells\"
ChDir strPath1
strExtension = Dir(strPath1 & "*.xls*")
Do While strExtension <> ""
Set wkbSource = Workbooks.Open(strPath1 & strExtension)
With wkbSource.Sheets("LowFlow GW front")
ActiveWindow.View = xlNormalView
On Error GoTo errHandler
Set wkbSource = ActiveWorkbook
Set wsA = ActiveSheet
'get active workbook folder, if saved
strPath = wkbSource.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
strName = wsA.Range("A1").Value _
& " - " & wsA.Range("A2").Value _
& " - " & wsA.Range("A3").Value
'create default name for savng file
strFile = wkbSource.Name & ".pdf"
strFile = Replace(strFile, ".xlsx", "")
strPathFile = "C:\Users\steve.argen\Documents\PPG\GW Sampling March 2020\PPG Balogna NUMBER 2\Final excel sheets\Final PDF\" & strFile
'export to PDF in current folder
wkbSource.Sheets(Array("LowFlow GW Front", "LowFlow GW Back")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
strPathFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
Application.CutCopyMode = False 'If you ever need to copy a large amount of info, this will hide any warnings
ActiveWindow.View = xlPageBreakPreview
End With
wkbSource.Close savechanges:=False
strExtension = Dir
Loop
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
This code
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
it should be at the end of the routine and not in the middle of the loop.

Excel Macro Saves as PDF

I have a Macro that applies some filters and then exports certain columns as a PDF file, currently the Macro saves the PDF in the same folder as the Excel file but I would like it to ask me where I want to save the file instead, is this possible?
Any help much appreciated! :)
Sub FilterSaveCases()
With ActiveSheet.PageSetup
.LeftHeader = "&B& &20 Doff Stock : " & Format(Now, " ddmmyyyy")
On Error Resume Next
Columns("H:H").AutoFilter.ShowAllData
Columns("H:H").AutoFilter
ActiveSheet.Range("H:H").AutoFilter Field:=1, Criteria1:=">1"
Columns("C:O").EntireColumn.Hidden = True
Columns("P:P").EntireColumn.Hidden = False
ActiveSheet.Pictures("Picture 1").Visible = False
Dim Nm As String
Dim Rng As Range
Set Rng = Range("A1:P198")
Nm = ActiveWorkbook.FullName
Nm = Left(Nm, InStrRev(Nm, ".") - 1) & Format(Now, " ddmmyyyy") & ".pdf"
Rng.ExportAsFixedFormat Type:=xlTypePDF, Filename:=Nm, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=True, OpenAfterPublish:=True
ActiveSheet.ShowAllData
Columns("C:O").EntireColumn.Hidden = False
Columns("M:M").EntireColumn.Hidden = True
Columns("P:P").EntireColumn.Hidden = True
ActiveSheet.Pictures("Picture 1").Visible = True
End With
End Sub
Yes, it is possible. Add this to your code. It will ask the user to select a location to save the file.
Sub download_location()
Dim user As String
Dim fldr As FileDialog
Dim sItem As String
Dim getfolder As String
user = Application.UserName
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
'do something here
End Sub

VBA Code only fully works when using breakpoint

I am running into an issue with the code below. The "Cash Flow" sheet will not change the height to fit onto one page. When I use a breakpoint it works but that line seems to be skip when running the macro.I have tried using Application.Wait but that did not work. Any thoughts on how I can fix it? Thanks in advance!
Section of the code that is not working:
Sheets("Cash Flow").Select
With ActiveSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
Full Code:
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
`enter code here` If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Sets Page Height ad Width
Dim myArray() As Variant
Dim i As Integer
For i = 1 To Sheets.Count
ReDim Preserve myArray(i - 1)
myArray(i - 1) = i
Next i
Sheets(myArray).Select
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 0
End With
Sheets("Cash Flow").Select
With ActiveSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
strName = CreateObject("Scripting.FileSystemObject").GetBaseName(ActiveWorkbook.Name)
'create default name for savng file
strFile = strName & ".pdf"
strPathFile = strPath & strFile
'export to PDF in current folder
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=strPathFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub

Resources