Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

VBA - Merging all Files from a folder directory into a single excel file

I have a folder directory with several excel files, and I have written code that copies every file in that directory to a single excel worksheet.

My only problem is that this folder has a few different categories of files, and I'm trying to find a way to ONLY copy the workbooks that start with the word "Marios". Can someone please advise on how I can add that file name condition? The code below successfully copies every file, but unfortunately I need to add a condition that states the file must contain "Marios" in the filename itself.

Option Explicit
    
Sub grabdata()
Dim FSO         As Object
Dim fsoFol      As Object
Dim fsoFile     As Object
Dim wb          As Workbook
Dim wksSource   As Worksheet
    
    
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set fsoFol = FSO.GetFolder("C:Desktop" & "")
    
    For Each fsoFile In fsoFol.Files
        If fsoFile.Type Like "Microsoft*Excel*Work*" _
        And Not fsoFile.Path = ThisWorkbook.FullName Then
            On Error GoTo 10
            
            Set wb = Workbooks.Open(fsoFile.Path, False, True)
            
           
            Set wksSource = Nothing
            On Error Resume Next
            Set wksSource = wb.Worksheets("Summary")
            
            If Not wksSource Is Nothing Then
                wksSource.Range("A1:i100").Copy _
                    ThisWorkbook.Worksheets("Nintendo").Cells(Rows.Count, 1).End(xlUp).Offset(1)
            End If
            
            On Error GoTo 0
            
            wb.Close False
        End If
    Next
10
End Sub
question from:https://stackoverflow.com/questions/65920314/vba-merging-all-files-from-a-folder-directory-into-a-single-excel-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simply add the check to your If statement.

If fsoFile.Type Like "Microsoft*Excel*Work*" _
   And Not fsoFile.Path = ThisWorkbook.FullName _
   And fsoFile.Name Like "Marios*" Then

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...