简体   繁体   中英

How can I return the file path of all files, within one folder? This is for Excel VBA

I have code that will allow me to return the file name of all files in a single folder. However, I would like to modify it to query a folder and return all the file paths of a particular file extension. (In this case .run files)

Any help would be appreciated! Thanks in advance.

        Option Explicit 

Sub GetFileNames() 

Dim xRow As Long 
Dim xDirect$, xFname$, InitialFoldr$ 

InitialFoldr$ = "G:\" '<<< Startup folder to begin searching from

       With Application.FileDialog(msoFileDialogFolderPicker) 
         .InitialFileName = Application.DefaultFilePath & "\" 
          .Title = "Please select a folder to list Files from" 
           .InitialFileName = InitialFoldr$ 
             .Show 
              If .SelectedItems.Count <> 0 Then 
                 xDirect$ = .SelectedItems(1) & "\" 
                 xFname$ = Dir(xDirect$, 7) 
                  Do While xFname$ <> "" 
                  ActiveCell.Offset(xRow) = xFname$ 
                  xRow = xRow + 1 
                   xFname$ = Dir 
              Loop 
          End If 
       End With 
   End Sub 

One more approach using Dir function:

Sub FilePaths()

Dim FileName As String
Dim FileMask As String
Dim InputFolder As String
Dim PathsArray() As String
Dim OutputRange As Range

InputFolder = "D:\DOCUMENTS\"
FileMask = "*.xls?"
Application.ScreenUpdating = False

FileName = Dir(InputFolder & FileMask)
ReDim PathsArray(0)
ThisWorkbook.ActiveSheet.Range("A1").CurrentRegion.ClearContents

Do While FileName <> ""
    PathsArray(UBound(PathsArray)) = InputFolder & FileName
    ReDim Preserve PathsArray(UBound(PathsArray) + 1)
    FileName = Dir
Loop

ReDim Preserve PathsArray(UBound(PathsArray))

Set OutputRange = ThisWorkbook.Sheets(1).Range("A1:A" & (UBound(PathsArray)))
OutputRange = WorksheetFunction.Transpose(PathsArray)
ThisWorkbook.ActiveSheet.Range("A1").CurrentRegion.Columns.AutoFit

Application.ScreenUpdating = True

MsgBox UBound(PathsArray) & " file(s) listed from folder:" & vbNewLine & InputFolder

End Sub

Source path & file mask ( wildcards *? are allowed ) should be defined.

Sample file is available: https://www.dropbox.com/s/j55p8otdiw67i7q/FilePaths.xlsm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM