Thursday, May 25, 2023

Select folder and get list file in folder (VBA)

 Sub Button2_Click()


    Dim oFSO As Object

    Dim oFolder As Object

    Dim oFile As Object

    Dim i As Integer

    Dim FldrPicker As FileDialog

    Dim myFolder As String


    'Have User Select Folder to Save to with Dialog Box

    Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)


    With FldrPicker

        .Title = "Select A Target Folder"

        .AllowMultiSelect = False

    If .Show <> -1 Then Exit Sub 'Check if user clicked cancel button

        myFolder = .SelectedItems(1) & "\"

    End With


    Set oFSO = CreateObject("Scripting.FileSystemObject")

    Set oFolder = oFSO.GetFolder(myFolder)


    For Each oFile In oFolder.Files

        Cells(i + 1, 1) = oFile.Name

        i = i + 1

    Next oFile

    

End Sub