简体   繁体   中英

Excel vba: Combine workbooks with same names

I use this code to merge more workbooks to one file. The problem that I discovered is that I have several worksheets with the same name and the code will stop. Any idea how can I fix this problem? For example, if I have 2 worksheets with the name "Sheet123" the program will stop.

 Sub mergeFiles()
'Merges all files in a folder to a main file.

 'Define variables:
  Dim numberOfFilesChosen, i As Integer
  Dim tempFileDialog As FileDialog
  Dim mainWorkbook, sourceWorkbook As Workbook
  Dim tempWorkSheet As Worksheet

  Set mainWorkbook = Application.ActiveWorkbook
  Set tempFileDialog = Application.FileDialog(msoFileDialogFilePicker)

  'Allow the user to select multiple workbooks
   tempFileDialog.AllowMultiSelect = True

   numberOfFilesChosen = tempFileDialog.Show

   'Loop through all selected workbooks
   For i = 1 To tempFileDialog.SelectedItems.Count

    'Open each workbook
    Workbooks.Open tempFileDialog.SelectedItems(i), Local:=True

    Set sourceWorkbook = ActiveWorkbook

    'Copy each worksheet to the end of the main workbook
    For Each tempWorkSheet In sourceWorkbook.Worksheets
        tempWorkSheet.Copy After:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)
    Next tempWorkSheet

    'Close the source workbook
    sourceWorkbook.Close
Next i

End Sub

Let us assume that you create a control sheet, you can try:

Option Explicit

Sub Loop_Sheets()

    Dim ws As Worksheet
    Dim LastRow As Long
    Dim wsName As String
    Dim wsList As Range, cell As Range
    Dim Excist As Boolean

    'Loop worksheets
    For Each ws In ThisWorkbook.Worksheets

        'Get Sheet name
        wsName = ws.Name

        With ThisWorkbook.Worksheets("Control")
            LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

            If LastRow = 1 Then
                .Cells(LastRow + 1, 1).Value = wsName
            Else
                'Set the list with worksheet names
                Set wsList = .Range(Cells(2, 1), Cells(LastRow, 1))

                Excist = False

                For Each cell In wsList
                    'Loop through list
                    If wsName = cell Then
                        Excist = True
                        Exit For
                    End If

                Next

                'If sheet appears in the list
                If Excist = True Then
                'Code'
                'If sheet dont appears in the list
                Else
                    .Cells(LastRow + 1, 1).Value = wsName
                    'Code'
                End If
            End If

        End With

    Next

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM