Combine multiple Excel workbooks into a single workbook

前端 未结 2 1632
广开言路
广开言路 2020-12-03 09:22

I am a novice at Visual Basic. I can use either Excel 2010 or Excel 2013 for this task.

I have dozens of workbooks with data on the first worksheet of each. For exam

相关标签:
2条回答
  • 2020-12-03 09:44

    The following accomplishes the task.

    Option Explicit
    
    Private Sub CommandButton1_Click()
    
    Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
    Dim WrdArray() As String
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    directory = "c:\test\"
    fileName = Dir(directory & "*.xl??")
    
    Do While fileName <> ""
        Workbooks.Open (directory & fileName)
            WrdArray() = Split(fileName, ".")
            For Each sheet In Workbooks(fileName).Worksheets
            Workbooks(fileName).ActiveSheet.Name = WrdArray(0)
                total = Workbooks("import-sheets.xlsm").Worksheets.Count
                Workbooks(fileName).Worksheets(sheet.Name).Copy after:=Workbooks("import-sheets.xlsm").Worksheets(total)
    
                GoTo exitFor:
    
            Next sheet
    
    exitFor:
        Workbooks(fileName).Close
        fileName = Dir()
    Loop
    
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    
    End Sub
    
    0 讨论(0)
  • 2020-12-03 09:45

    In Excel press Alt+F11, this will open the Excel VBA editor.

    Article http://www.excel-spreadsheet.com/vba/debugging.htm explains some basics how to use it.

    In Module1 there are 2 short subroutines opensheets and merge containing ~50 lines of code.

    Use F1 with cursor within words you don't understand, to learn what it means.

    Once you understand what the code does, you can tailor it to your needs.

    0 讨论(0)
提交回复
热议问题