[008]VBA合并多个excel文件下所有工作表(一簿多表到新建工作簿).txt
Sub 合并多个excel下所有活动工作表()
    '定义对话框变量,并以一个工作簿多工作表合并
    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    
    '新建一个工作簿
    Dim newwb As Workbook
    Set newwb = Workbooks.Add
    
    With fd
        If .Show = -1 Then
            '定义单个文件变量
            Dim vrtSelectedItem As Variant
            
            '定义循环变量
            Dim i As Integer
            i = 1
            
            '开始文件检索
            For Each vrtSelectedItem In .SelectedItems
                '打开被合并工作簿
                Dim tempwb As Workbook
                Set tempwb = Workbooks.Open(vrtSelectedItem)
                
                '定义工作表变量
                Dim tempws As Worksheet
                
                '循环复制每个工作表
                For Each tempws In tempwb.Worksheets
                    '检查工作表名是否已存在
                    Dim counter As Integer
                    counter = 0
                    While WorksheetExists(tempws.Name & IIf(counter > 0, "_" & counter, ""), newwb)
                        counter = counter + 1
                    Wend
                    
                    '复制工作表并重命名
                    tempws.Copy Before:=newwb.Worksheets(i)
                    newwb.Worksheets(i).Name = tempws.Name & IIf(counter > 0, "_" & counter, "")
                    
                    i = i + 1
                Next tempws
                
                '关闭被合并工作簿
                tempwb.Close SaveChanges:=False
            Next vrtSelectedItem
        End If
    End With
    
    Set fd = Nothing
    MsgBox Prompt:="合并完成", Buttons:=vbInformation + vbOKCancel, Title:="逗号Office技巧"
End Sub
Function WorksheetExists(shtName As String, wb As Workbook) As Boolean
    '检查工作表名是否已存在
    Dim sht As Worksheet
    Dim shtFound As Boolean
    
    For Each sht In wb.Worksheets
        If sht.Name = shtName Then
            shtFound = True
            Exit For
        End If
    Next
    
    WorksheetExists = shtFound
End Function
返回视频教程