The `Dir` function in VBA (Visual Basic for Applications) is used to return the name of a file, directory, or folder that matches a specified pattern or attributes. It is often used to loop through files or folders in a directory. The function can return one file name at a time, and it must be called repeatedly to get additional file names.
Here’s the syntax for the `Dir` function:
Dir([pathname], [attributes])
- `pathname`: This is an optional string argument that specifies the file name or a directory or folder, and it can include wildcard characters (* and ?) for file name matching.
- `attributes`: This is an optional argument that specifies file attributes to search for, such as `vbReadOnly`, `vbHidden`, `vbSystem`, `vbDirectory`, `vbArchive`, or `vbNormal`, as well as combinations using the OR operator.
Here’s an example of how you can use the `Dir` function in VBA to loop through all the `.xlsx` files in a directory:
Sub ListExcelFiles()
Dim folderPath As String
Dim fileName As String
' Specify the folder path
folderPath = "C:Files"