VBA Opening Save Window Despite Events and Alerts Being Off - excel

All I am trying to do is save one sheet out of the workbook to a new workbook in the same folder.
But every time I run my code, excel interrupts the execution and opens up the Save As window where you have to select the folder and name of the file, which I have never seen before.
Any Ideas on how to circumvent this? I have Events and Alerts off.
Code:
Sub Export_Data()
Dim ws As Worksheet, wb As Workbook
Dim name As String
Dim lcol As Double, lrow As Double
Dim path As String
Set ws = ThisWorkbook.Worksheets("EMPLOYEES")
Application.DisplayAlerts = False
Application.EnableEvents = False
path = "C:\Users\PATH\"
Set wb = Workbooks.Add
ws.Copy Before:=wb.Sheets(1)
On Error Resume Next ' Need this because I get a runtime error 1004, though it still saves it regardless
wb.SaveAs Filename:=path & "People_Data" & ".xlsx", FileFormat:=51 '''' Here is where it opens the save as window??????
wb.Sheets("Sheet1").Delete
wb.Close SaveChanges:=True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub

Save a Worksheet to a New Workbook
If nothing else, this should shed some light on what's going on. Your feedback is expected.
Sub SaveWorksheetToNewWorkbook()
Const ProcName As String = "SaveWorksheetToNewWorkbook"
Dim Success As Boolean
On Error GoTo ClearError
Const SOURCE_WORKSHEET_NAME As String = "EMPLOYEES"
Const DESTINATION_FOLDER_PATH As String = "C:\Test"
Const DESTINATION_FILE_NAME As String = "People_Data.xlsx"
Application.ScreenUpdating = False
' Check if the destination path exists.
Dim pSep As String: pSep = Application.PathSeparator
Dim dFolderPath As String: dFolderPath = DESTINATION_FOLDER_PATH
If Right(dFolderPath, 1) <> pSep Then dFolderPath = dFolderPath & pSep
Dim dFolderName As String: dFolderName = Dir(dFolderPath, vbDirectory)
If Len(dFolderName) = 0 Then
MsgBox "The path '" & dFolderPath & "' doesn't exist.", _
vbExclamation, ProcName
Exit Sub
End If
Dim dwb As Workbook
' Check if the destination workbook, or a workbook with the same name,
' is open.
On Error Resume Next
Set dwb = Workbooks(DESTINATION_FILE_NAME)
On Error GoTo ClearError
If Not dwb Is Nothing Then
If StrComp(dwb.Path & pSep, dFolderPath, vbTextCompare) = 0 Then
MsgBox "The destination workbook '" & DESTINATION_FILE_NAME _
& "' is open." & vbLf & "Close it and try again.", _
vbExclamation, ProcName
Else
MsgBox "A workbook with the same name as the destination file ('" _
& DESTINATION_FILE_NAME & "') is open." _
& vbLf & "Close it and try again.", vbExclamation, ProcName
End If
Exit Sub
End If
' Export the worksheet.
Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = swb.Worksheets(SOURCE_WORKSHEET_NAME)
sws.Copy ' creates a copy as a new single-worksheet workbook
Set dwb = Workbooks(Workbooks.Count)
Dim ErrNumber As Long
Dim ErrDescription As String
Application.DisplayAlerts = False ' overwrite without confirmation
On Error Resume Next
dwb.SaveAs dFolderPath & DESTINATION_FILE_NAME
ErrNumber = Err.Number
ErrDescription = Err.Description
On Error GoTo ClearError
Application.DisplayAlerts = True
dwb.Close SaveChanges:=False ' just got saved
If ErrNumber <> 0 Then
MsgBox "' Run-time error '" & ErrNumber & "':" & vbLf _
& ErrDescription & vbLf & vbLf _
& "This error occurred while attempting to save the workbook.", _
vbCritical, ProcName
Exit Sub
End If
Success = True
ProcExit:
On Error Resume Next
If Success Then
MsgBox "Worksheet saved to new workbook.", vbInformation, ProcName
End If
On Error GoTo 0
Exit Sub
ClearError:
MsgBox "' Run-time error '" & Err.Number & "':" & vbLf _
& Err.Description & vbLf & vbLf _
& "This error occurred quite unexpectedly.", _
vbCritical, ProcName
Resume ProcExit
End Sub

Related

Why do I get run-time error 9 message: Expecting object to be local when I run this code?

I am in need of assistance in resolving an issue I have ‎been experiencing when running certain codes, ‎particularly the one listed below. While I ‎comprehend why this error message may appear, I ‎am unsure as to why it is occurring with this ‎particular code. I have been receiving the 'expecting ‎object to be local' error message and 'subscript out ‎of range error message when no sheet with the ‎name is declared in the, despite the code's purpose ‎being to determine if the sheet is already present or ‎not and create it if it does not exist.‎
I'll be thankful to those who would put a hand into ‎this.‎
By the way, the code stops at the step of setting the WS.
Sub Check_Sheet_Exists()
Dim WS As Worksheet
Dim SheetName As String
SheetName = "ABCD"
' On Error Resume Next
Set WS = ThisWorkbook.Sheets(SheetName)
If WS Is Nothing Then
Sheets.Add before:=Sheets(Sheets.Count)
ActiveSheet.Name = SheetName
MsgBox "The sheet '" & SheetName & "' was created."
Else
MsgBox "The sheet '" & SheetName & "' already exists."
End If
End Sub
Code stuck here
Someone help me solve this issue, please.
Added an explicit Workbook reference, and cancelling the OERN as suggested by VBasic2008
Sub Check_Sheet_Exists()
Dim WS As Worksheet, wb As Workbook
Dim SheetName As String 'Use Const if the name is fixed...
SheetName = "ABCD"
Set wb = ThisWorkbook
On Error Resume Next 'ignore errors
Set WS = wb.Sheets(SheetName)
On Error GoTo 0 'stop ignoring errors
If WS Is Nothing Then
Set WS = wb.Worksheets.Add(before:=wb.Sheets(wb.Sheets.Count))
WS.Name = SheetName
MsgBox "The sheet '" & SheetName & "' was created."
Else
MsgBox "The sheet '" & SheetName & "' already exists."
End If
End Sub
Add Worksheet With Specific Name
Sub AddWorksheet()
On Error GoTo ClearError
Const PROC_TITLE As String = "Add Worksheet"
Const SHEET_NAME As String = "A\BCD"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Check if sheet name is taken.
Dim sh As Object
On Error Resume Next
Set sh = wb.Sheets(SHEET_NAME)
On Error GoTo ClearError
If Not sh Is Nothing Then
MsgBox "The sheet """ & SHEET_NAME & """ already exists.", _
vbExclamation, PROC_TITLE
Exit Sub
End If
' Add the worksheet.
Dim ws As Worksheet
Set ws = wb.Sheets.Add(Before:=wb.Sheets(wb.Sheets.Count)) ' before last
'Set ws = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count)) ' last
'Set ws = wb.Sheets.Add(Before:=wb.Sheets(1)) ' first
' Rename the worksheet.
Dim ErrNumber As Long, ErrDescription As String
' Atempt to rename.
On Error Resume Next
ws.Name = SHEET_NAME
ErrNumber = Err.Number
ErrDescription = Err.Description
On Error GoTo ClearError
' Invalid Sheet Name.
If ErrNumber <> 0 Then
Application.DisplayAlerts = False ' to delete without confirmation
ws.Delete
Application.DisplayAlerts = True
MsgBox "Run-time error '" & ErrNumber & vbLf & vbLf _
& ErrDescription & vbLf & vbLf & vbLf & PROC_TITLE & " Info" _
& vbLf & "The name """ & SHEET_NAME & _
""" is invalid. Worksheet not added.", vbCritical, PROC_TITLE
Exit Sub
End If
' Valid Sheet Name
MsgBox "The worksheet """ & SHEET_NAME & """ was added.", _
vbInformation, PROC_TITLE
ProcExit:
Exit Sub
ClearError:
MsgBox "Run-time error '" & Err.Number & vbLf & vbLf _
& Err.Description & vbLf & vbLf & vbLf & PROC_TITLE & " Info" _
& vbLf & "An unexpected error occurred.", _
vbCritical, PROC_TITLE
Resume ProcExit
End Sub

Create and open folder modify path

I use the code below to create and open a folder from excel when I press a button but I want the created folder to be in the same location like the excel workbook. Can you please help me modif the code? Thank you!
Sub btn1_click()
Dim dir As String
Dim fso As Object
Dim path As String
path = Application.ActiveWorkbook.path
dir = ActiveCell.value
Set fso = CreateObject("scripting.filesystemobject")
If Not fso.folderexists(dir) Then
fso.createfolder (dir)
End If
Call Shell("explorer.exe" & " " & dir, vbNormalFocus)
End Sub
Create and Explore a Subfolder Using the Active Cell's Value
The code is written for any active cell so be a little careful how you use it to not end up with folders in the wrong places.
If you run it by using a button, you are ensuring that it will use the right cell since the active sheet is the one containing the button and containing the active cell.
Sub CreateActiveCellSubFolder()
Const ExploreIfSubFolderExists As Boolean = True
Dim ash As Object: Set ash = ActiveSheet ' it could be a chart
If ash Is Nothing Then ' no active sheet
MsgBox "No visible workbooks open.", _
vbCritical
Exit Sub
End If
If ash.Type <> xlWorksheet Then
MsgBox "The active sheet '" & ash.Name & "' is not a worksheet.", _
vbCritical
Exit Sub
End If
Dim wb As Workbook: Set wb = ash.Parent
If Len(wb.Path) = 0 Then
MsgBox "The workbook '" & wb.Name & "' containing the active sheet '" _
& ash.Name & "' has not been saved yet.", _
vbCritical
Exit Sub
End If
' If the active sheet is a worksheet, it has an active cell at any time,
' no matter what is selected.
Dim aCell As Range: Set aCell = ActiveCell
Dim SubFolderName As String: SubFolderName = CStr(ActiveCell.Value)
If Len(SubFolderName) = 0 Then
MsgBox "The cell '" & aCell.Address(0, 0) & "' is blank.", _
vbCritical
Exit Sub
End If
Dim SubFolderPath As String
SubFolderPath = wb.Path & Application.PathSeparator & SubFolderName
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FolderExists(SubFolderPath) Then
MsgBox "The folder '" & SubFolderName & "' already exists.", _
vbInformation
If Not ExploreIfSubFolderExists Then Exit Sub
Else
Dim ErrNum As Long
On Error Resume Next
fso.CreateFolder SubFolderPath
ErrNum = Err.Number
' If ErrNum > 0 Then
' Debug.Print "Run-time error '" & Err.Number & "': " _
' & Err.Description
' End If
On Error GoTo 0
If ErrNum = 0 Then
MsgBox "Created the folder '" & SubFolderName & "'.", _
vbInformation
Else
MsgBox "Could not create the folder '" & SubFolderName & "'.", _
vbCritical
Exit Sub
End If
End If
wb.FollowHyperlink SubFolderPath
End Sub

Export all visible sheets to PDFs

I'm using below code to export all visible sheets to PDFs. It has worked fine for months for me and my colleagues, and still does on my computer. However, on 2 colleagues' computers, the
runtime error -2147319767 (80028029)
started occurring recently.
I've seen similar threads mentioning this error but still don't see how to solve it in this case.
Sub ExportToPDFs()
Dim ws As Worksheet
For Each ws In Worksheets
If ws.Visible = -1 Then
ws.Select
nm = ws.Name
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="D:\Test\" & nm & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Next ws
End Sub
Export Visible Worksheets to PDF
Option Explicit
Sub ExportToPDFs()
On Error GoTo ClearError
Const FolderPath As String = "C:\Test\T2022\72571395\"
Const FileExtension As String = ".pdf" ' fixed; do not change
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Alternatives:
'Set wb = ActiveWorkbook ' workbook you're looking at
'Set wb = Workbooks("Test.xlsx") ' a specific open workbook
'Set wb = Workbooks.Open("D:\Test\Test.xlsx") ' a specific closed workbook
' Export worksheets.
Dim ws As Worksheet
Dim FileCount As Long
Dim ErrorFileCount As Long
Dim FilePath As String
Dim MsgString As String
Dim ErrorMsgString As String
Dim AnExportErrorOccurred As Boolean
For Each ws In wb.Worksheets
If ws.Visible = xlSheetVisible Then
FilePath = FolderPath & ws.Name & FileExtension
On Error GoTo ExportError
ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FilePath, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
On Error GoTo ClearError
If AnExportErrorOccurred Then
AnExportErrorOccurred = False
Else
MsgString = MsgString & vbLf & FilePath
FileCount = FileCount + 1
End If
'Else ' not visible; do nothing
End If
Next ws
' Inform.
Select Case FileCount
Case 0
MsgString = "No files exported."
Case 1
MsgString = "The following file was created:" & MsgString
Case Else
MsgString = "The following " & FileCount & " files were created:" _
& MsgString
End Select
Select Case ErrorFileCount
Case 0
' do nothing
Case 1
ErrorMsgString = "The following file was not created:" & ErrorMsgString
If FileCount = 0 Then
MsgString = ErrorMsgString
Else
MsgString = MsgString & vbLf & vbLf & ErrorMsgString
End If
Case Else
ErrorMsgString = "The following " & ErrorFileCount _
& " files were not created:" & ErrorMsgString
If FileCount = 0 Then
MsgString = ErrorMsgString
Else
MsgString = MsgString & vbLf & vbLf & ErrorMsgString
End If
End Select
If FileCount = 0 Then
If ErrorFileCount = 0 Then
MsgBox MsgString, vbExclamation
Else
MsgBox MsgString, vbCritical
End If
Else
If ErrorFileCount = 0 Then
MsgBox MsgString, vbInformation
Else
MsgBox MsgString, vbCritical
End If
End If
ProcExit:
Exit Sub
ExportError:
Debug.Print "Run-time error '" & Err.Number & "': " & Err.Description
ErrorMsgString = vbLf & FilePath
ErrorFileCount = ErrorFileCount + 1
AnExportErrorOccurred = True
Resume Next
ClearError:
Debug.Print "Run-time error '" & Err.Number & "': " & Err.Description
Resume ProcExit
End Sub

VBA always crash on Excel 2010

I have some code that I make using Excel 2013. It works perfectly and when I try to run it on Excel 2010, the excel always does not respond, restarting the program and closing. I try to reopen it and the file sometimes goes with read-only or recovery mode so I can't even run my macro even I enable it.
Is there any way to fix this without updating the excel? any ideas?
NB: the laptop with Excel 2010 is not mine, it's my user laptop so if possible, I prefer to not change anything inside the laptop
here's the code
Public Const paramFolderPath = "C:\Users\Documents\Data"
Sub Sheet1()
Application.ScreenUpdating = False
OpenWorkbooks paramFolderPath 'Path collected from the folder parameter
Application.ScreenUpdating = True
End Sub
Sub OpenWorkbooks(sourceFolder As Variant)
Dim sourceFile As String 'Filename obtained by DIR function
Dim masterWb, Sourcewb As Workbook 'Used to loop through each workbook
Dim ext As String
On Error Resume Next
Application.ScreenUpdating = False
Set masterWb = ThisWorkbook
sourceFile = Dir(sourceFolder & "\") 'DIR gets the first file of the folder
Do While sourceFile <> ""
ext = Right(sourceFile, Len(sourceFile) - InStrRev(sourceFile, "."))
If sourceFile <> ThisWorkbook.Name And (ext = "xlsm" Or ext = "xlsx") Then
Workbooks.Open Filename:=sourceFolder & "\" & sourceFile, ReadOnly:=True
Set Sourcewb = ActiveWorkbook
'Copy only the first sheet of a workbook
Sourcewb.Worksheets(1).Copy after:=masterWb.Sheets(masterWb.Worksheets.Count)
'Close the source workbook
Sourcewb.Close SaveChanges:=False
Set Sourcewb = Nothing
End If
sourceFile = Dir 'DIR gets the next file in the folder
Loop
On Error GoTo 0
Application.ScreenUpdating = True
End Sub
Loop Through Files in a Folder
Option Explicit
Public Const paramFolderPath = "C:\Users\Documents\Data"
Sub GetFirstWorkSheets()
ImportFirstWorksheets paramFolderPath
End Sub
Sub ImportFirstWorksheets(ByVal sFolderPath As String)
Const ProcName As String = "ImportFirstWorksheets"
Dim fCount As Long
Dim wbCount As Long
Dim wsCount As Long
On Error GoTo ClearError
Const ExtensionsList As String = "xlsm,xlsx"
' Check if files in folder.
If Right(sFolderPath, 1) <> "\" Then sFolderPath = sFolderPath & "\"
Dim sFileName As String: sFileName = Dir(sFolderPath)
If Len(sFileName) = 0 Then
MsgBox "No files found in '" & sFolderPath & "'.", _
vbExclamation, ProcName
Exit Sub
End If
Dim Extensions() As String: Extensions = Split(ExtensionsList, ",")
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim dwbPath As String: dwbPath = dwb.FullName
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim swb As Workbook
Dim Ext As String
Dim sFilePath As String
Do While Len(sFileName) > 0
fCount = fCount + 1
Ext = Right(sFileName, Len(sFileName) - InStrRev(sFileName, "."))
If IsNumeric(Application.Match(Ext, Extensions, 0)) Then
wbCount = wbCount + 1
sFilePath = sFolderPath & sFileName
If StrComp(sFilePath, dwbPath, vbTextCompare) <> 0 Then
Application.DisplayAlerts = False
On Error GoTo WbError
Set swb = Workbooks.Open(sFilePath, , True)
On Error GoTo ClearError
Application.DisplayAlerts = True
End If
If Not swb Is Nothing Then
If swb.Worksheets.Count > 0 Then ' only first worksheet
wsCount = wsCount + 1
swb.Worksheets(1).Copy After:=dwb.Sheets(dwb.Sheets.Count)
End If
swb.Close SaveChanges:=False
Set swb = Nothing
End If
End If
sFileName = Dir ' next file in folder
Loop
SafeExit:
On Error Resume Next
If Not Application.EnableEvents Then
Application.EnableEvents = True
Application.ScreenUpdating = True
End If
MsgBox "Files Found: " & fCount & vbLf _
& "Workbooks Found: " & wbCount & vbLf _
& "Worksheets Copied: " & wsCount, vbInformation, ProcName
On Error GoTo 0
Exit Sub
WbError:
Debug.Print "'" & ProcName & "' Run-time error '" _
& Err.Number & "':" & vbLf & " " & Err.Description
Resume Next
ClearError:
Debug.Print "'" & ProcName & "' Run-time error '" _
& Err.Number & "':" & vbLf & " " & Err.Description
Resume SafeExit
End Sub

runtime Error 9 when opening excel workbook in a folder to copy specific sheet

I need help to handle runtime error 9.
My goals is to create a new workbook that compile specific sheet (Master User) from all excel workbook in a folder.
I'm stuck while using "on error goto" because i don't get it how to set the program while error (sheet doesn't exist) goto next workbook.
My code now cause me stuck in an never ending loop on a workbook that didn't have "master user" sheet
Sub Master()
Dim MyFiles As String
Dim Path As String
Dim myExtension As String
Dim Filename As String
Workbooks.Add.SaveAs Filename:="Master", FileFormat:=51
Path = "D:\My Document\"
myExtension = "*.xls*"
MyFiles = Dir(Path & myExtension)
On Error GoTo test
DoAgain:
Do While MyFiles <> ""
Workbooks.Open (Path & MyFiles)
Sheets("master user").Select
ActiveSheet.Rows(1).Copy
Workbooks("Master.xlsx").Activate
Sheets.Add After:=Sheets(Sheets.Count)
Range("A1").PasteSpecial xlPasteAll
If InStr(MyFiles, ".") > 0 Then
Filename = Left(MyFiles, InStr(MyFiles, ".") - 1)
End If
ActiveSheet.Name = Filename
Workbooks(Filename).Activate
Application.CutCopyMode = False
ActiveWorkbook.Close SaveChanges:=False
MyFiles = Dir
Loop
Workbooks("Master.xlsx").Activate
ActiveWorkbook.Close SaveChanges:=True
test:
ActiveWorkbook.Close SaveChanges:=False
Resume DoAgain
ActiveWorkbook.Save
End Sub
Copy Worksheet Ranges From Multiple Workbooks to a New Workbook
The Workbooks
The workbook containing this code (ThisWorkbook).
The source workbook i.e. each workbook (file) found in the source folder.
The destination workbook i.e. a newly added workbook that will be copied to.
Description
This will copy the first row of a same-named worksheet of each workbook (file) found in a folder to a newly added (and renamed) worksheet (multiple) of a new workbook (one).
Option Explicit
Sub CreateMaster()
Const ProcName As String = "CreateMaster"
On Error GoTo ClearError
' Source
Const sFolderPath As String = "D:\My Document\" ' maybe a missing 's'?
Const sFilePattern As String = "*"
Const sExtensionPattern As String = ".xls*"
Const swsName As String = "Master User"
' Destination
Const dFileName As String = "Master.xlsx"
' You never mentioned the destination path ('Master.xlsx') so I chose
' the same path as the path of the workbook containing this code.
' Omitting this path will lead to unexpected results (errors).
Dim dFilePath As String: dFilePath = ThisWorkbook.Path & "\"
Dim dFileFormat As XlFileFormat: dFileFormat = xlOpenXMLWorkbook
' Check if the source folder exists.
If Len(Dir(sFolderPath, vbDirectory)) = 0 Then
MsgBox "The folder '" & sFolderPath & "' doesn't exist.", _
vbCritical, ProcName
Exit Sub
End If
' Return the paths of the files of the source folder in a collection.
Dim sFilePaths As Collection
Set sFilePaths = CollFilePaths(sFolderPath, sFilePattern, sExtensionPattern)
If sFilePaths Is Nothing Then ' no files found
MsgBox "No '" & sExtensionPattern & "'- files found in folder '" _
& sFolderPath & "'.", vbCritical, ProcName
Exit Sub
End If
Application.ScreenUpdating = False
Dim swb As Workbook
Dim sws As Worksheet
Dim sFilePath As Variant
Dim dwb As Workbook
Dim dws As Worksheet
Dim dwbCreated As Boolean
' Loop through the elements (file paths) of the collection.
For Each sFilePath In sFilePaths
Set swb = Workbooks.Open(sFilePath)
' Attempt to create a reference to the source worksheet.
On Error Resume Next
Set sws = swb.Worksheets(swsName)
On Error GoTo ClearError
If Not sws Is Nothing Then ' source worksheet exists
' Add a new worksheet/workbook.
If dwbCreated Then ' destination workbook created
Set dws = dwb.Worksheets _
.Add(After:=dwb.Sheets(dwb.Sheets.Count))
Else ' destination workbook not created
Set dwb = Workbooks.Add(xlWBATWorksheet) ' one worksheet
Set dws = dwb.Worksheets(1)
dwbCreated = True
End If
' Attempt to rename the destination worksheet.
On Error Resume Next
dws.Name = Left(swb.Name, InStrRev(swb.Name, ".") - 1)
On Error GoTo ClearError
' Copy source to destination.
sws.Rows(1).Copy dws.Rows(1)
Set sws = Nothing
'Else ' source worksheet doesn't exist
End If
swb.Close SaveChanges:=False
Next sFilePath
If dwbCreated Then
dwb.Worksheets(1).Activate
Application.DisplayAlerts = False ' overwrite without confirmation
dwb.SaveAs dFilePath & dFileName, dFileFormat
Application.DisplayAlerts = True
dwb.Close
MsgBox "Master created.", vbInformation, ProcName
Else
MsgBox "Non of the opened workbooks contained a worksheet " _
& "named '" & swsName & "'.", vbExclamation, ProcName
End If
Application.ScreenUpdating = False
ProcExit:
Exit Sub
ClearError:
Debug.Print "'" & ProcName & "' Run-time error '" _
& Err.Number & "':" & vbLf & " " & Err.Description
Resume ProcExit
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Returns the paths of the files of a folder in a collection.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function CollFilePaths( _
ByVal FolderPath As String, _
Optional ByVal FilePattern As String = "*", _
Optional ByVal ExtensionPattern As String = "*") _
As Collection
Const ProcName As String = "CollFilePaths"
On Error GoTo ClearError
Dim pSep As String: pSep = Application.PathSeparator
Dim foPath As String: foPath = FolderPath
If Right(foPath, 1) <> pSep Then foPath = foPath & pSep
Dim ePattern As String: ePattern = ExtensionPattern
If Left(ePattern, 1) <> "." Then ePattern = "." & ePattern
Dim fiName As String: fiName = Dir(foPath & FilePattern & ePattern)
If Len(fiName) = 0 Then Exit Function
Dim coll As Collection: Set coll = New Collection
Do Until Len(fiName) = 0
coll.Add foPath & fiName
fiName = Dir
Loop
Set CollFilePaths = coll
ProcExit:
Exit Function
ClearError:
Debug.Print "'" & ProcName & "' Run-time error '" _
& Err.Number & "':" & vbLf & " " & Err.Description
Resume ProcExit
End Function

Resources