Различные методы перебора файлов в папке с использованием VBA

Чтобы перебрать все файлы в папке с помощью VBA, вы можете использовать различные методы. Вот несколько примеров:

Метод 1: использование функции Dir

Sub IterateFilesUsingDir()
    Dim folderPath As String
    Dim fileName As String

    folderPath = "C:\Your\Folder\Path\" ' Update with your folder path

    fileName = Dir(folderPath & "*.*", vbNormal)

    Do While fileName <> ""
        ' Process the file
        Debug.Print fileName

        fileName = Dir
    Loop
End Sub

Метод 2: использование FileSystemObject
Чтобы использовать FileSystemObject, необходимо добавить ссылку на библиотеку «Microsoft Scripting Runtime». Вот пример перебора файлов в папке с помощью FileSystemObject:

Sub IterateFilesUsingFileSystemObject()
    Dim folderPath As String
    Dim fileSystem As Object ' FileSystemObject
    Dim folder As Object ' Folder
    Dim file As Object ' File

    folderPath = "C:\Your\Folder\Path\" ' Update with your folder path

    Set fileSystem = CreateObject("Scripting.FileSystemObject")
    Set folder = fileSystem.GetFolder(folderPath)

    For Each file In folder.Files
        ' Process the file
        Debug.Print file.Name
    Next file
End Sub

Метод 3: использование элемента управления DirListBox (требуется UserForm)
Этот метод предполагает использование пользовательской формы с элементом управления DirListBox. Вот пример:

Sub IterateFilesUsingDirListBox()
    Dim userForm As UserForm1 ' Update with your UserForm name

    Set userForm = New UserForm1
    userForm.Show

    Dim folderPath As String
    Dim fileName As String

    folderPath = userForm.Dir1.Path

    fileName = Dir(folderPath & "\*.*", vbNormal)

    Do While fileName <> ""
        ' Process the file
        Debug.Print fileName

        fileName = Dir
    Loop
End Sub