首页 > 解决方案 > 合并文件,文件名中包含某些文本;从文件夹目录到单个 Excel 文件

问题描述

我有一个包含几个 Excel 文件的文件夹目录。我编写的代码将该目录中的每个文件复制到一个 Excel 工作表中。

这个文件夹有几个不同类别的文件。

我需要添加一个条件,说明文件必须在文件名中包含“Marios”。

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

标签: excelvba

解决方案


只需将检查添加到您的 If 语句中。

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

推荐阅读