SOLVED

Select all files in a folder automatically

Copper Contributor

Hello,

 

I have a code for fussing with several sheets in the same folder by but you have to select the files manually:

minhhai91_0-1625042596352.png

this is the code I actually have

 

minhhai91_1-1625042670064.png

This is the code i want to keep and I would like to add automatic selection of all files in a folder

 

Thanks in advance.

 

Frédéric

4 Replies

@minhhai91 

Here you go:

Sub Fusionner()
    Dim wbFusion As Workbook
    Dim wbCible As Workbook
    Dim shCible As Worksheet
    Dim stDossier As String
    Dim stFichier As String
    
    With Application.FileDialog(4) ' msoFileDialogFolderPicker
        .InitialFileName = ThisWorkbook.Path
        If .Show Then
            stDossier = .SelectedItems(1) & Application.PathSeparator
        Else
            Beep
            Exit Sub
        End If
    End With
    
    Set wbFusion = ThisWorkbook
    
    stFichier = Dir(stDossier & "*.xls*")
    Do While stFichier <> ""
        Set wbCible = Workbooks.Open(stDossier & stFichier)
        For Each shCible In wbCible.Worksheets
            shCible.Copy After:=wbFusion.Worksheets(wbFusion.Worksheets.Count)
        Next shCible
        wbCible.Close SaveChanges:=False
        stFichier = Dir
    Loop
End Sub
Thanks for your anwser.

how can I add a path so I don't have to manually select the folder ?
best response confirmed by minhhai91 (Copper Contributor)
Solution

@minhhai91 

Replace

    With Application.FileDialog(4) ' msoFileDialogFolderPicker
        .InitialFileName = ThisWorkbook.Path
        If .Show Then
            stDossier = .SelectedItems(1) & Application.PathSeparator
        Else
            Beep
            Exit Sub
        End If
    End With

with a line that specifies the path:

    stDossier = "C:\MyFolder\MySubfolder\"

The path must end in a backslash \

Thank you very much, it work.
1 best response

Accepted Solutions
best response confirmed by minhhai91 (Copper Contributor)
Solution

@minhhai91 

Replace

    With Application.FileDialog(4) ' msoFileDialogFolderPicker
        .InitialFileName = ThisWorkbook.Path
        If .Show Then
            stDossier = .SelectedItems(1) & Application.PathSeparator
        Else
            Beep
            Exit Sub
        End If
    End With

with a line that specifies the path:

    stDossier = "C:\MyFolder\MySubfolder\"

The path must end in a backslash \

View solution in original post