我对VB编码很陌生,正在尝试合并Excel电子表格,然后将数据合并到一个电子表格中。我发现this code可以很好地工作,直到遇到具有相同工作表名称的文件。
Sub MergeExcelFiles()
Dim fnameList, fnameCurFile As Variant
Dim countFiles, countSheets As Integer
Dim wksCurSheet As Worksheet
Dim wbkCurBook, wbkSrcBook As Workbook
fnameList = Application.GetOpenFilename(FileFilter:="Microsoft Excel Workbooks (*.xls;*.xlsx;*.xlsm),*.xls;*.xlsx;*.xlsm", Title:="Choose Excel files to merge", MultiSelect:=True)
If (vbBoolean <> VarType(fnameList)) Then
If (UBound(fnameList) > 0) Then
countFiles = 0
countSheets = 0
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set wbkCurBook = ActiveWorkbook
For Each fnameCurFile In fnameList
countFiles = countFiles + 1
Set wbkSrcBook = Workbooks.Open(Filename:=fnameCurFile)
For Each wksCurSheet In wbkSrcBook.Sheets
countSheets = countSheets + 1
wksCurSheet.Copy after:=wbkCurBook.Sheets(wbkCurBook.Sheets.Count)
Next
wbkSrcBook.Close SaveChanges:=False
Next
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
MsgBox "Processed " & countFiles & " files" & vbCrLf & "Merged " & countSheets & " worksheets", Title:="Merge Excel files"
End If
Else
MsgBox "No files selected", Title:="Merge Excel files"
End If
End Sub
运行此代码时,我得到一个
运行时错误“ 1004”: 无法将工作表重命名为与另一个工作表,被引用的对象库或Visual Basic引用的工作簿相同。
在导入工作表时,我需要重命名。
答案 0 :(得分:0)
在Excel2016中,不能重新创建此问题,因为Excel会自动将“(1)”,“(2)” ...添加到与已复制工作表同名的工作表名称中。
如果您使用的是旧版Excel,则需要重新创建此行为才能解决此问题。
要重命名工作表,我引用了以下答案:Excel rename sheet with if sheet name already exists
创建一个新功能来检查两个工作簿中的工作表名称:
Private Function VerifySheetName(ByVal sourceWorkbook As Workbook, ByVal targetWorkbook As Workbook, ByVal sheetName As String) As String
Dim combinedSheets As New Collection
Dim tempSheet As Worksheet
For Each tempSheet In sourceWorkbook.Sheets
combinedSheets.Add tempSheet
Next tempSheet
For Each tempSheet In targetWorkbook.Sheets
combinedSheets.Add tempSheet
Next tempSheet
For Each tempSheet In combinedSheets
If tempSheet.Name = sheetName Then
VerifySheetName = sheetName & "_" & combinedSheets.Count
End If
Next tempSheet
End Function
在循环中调用此函数:
For Each wksCurSheet In wbkSrcBook.Sheets
tempSheetName = VerifySheetName(wbkSrcBook, wbkCurBook, wksCurSheet.Name)
If Not wksCurSheet.Name = tempSheetName Then
wksCurSheet.Name = tempSheetName
End If
countSheets = countSheets + 1
wksCurSheet.Copy after:=wbkCurBook.Sheets(wbkCurBook.Sheets.Count)
Next
如果您使用的是Option Explicit
,也不要忘记添加新的变量声明(应该!)
Dim tempSheetName As String
P.S。 在同一行中启动多个变量时,如果省略变量类型,则默认情况下将其转换为变量:
Dim countFiles, countSheets As Integer
在这种情况下,countFiles是变量类型,而countSheets是整数类型。如果需要显式可变类型,则需要为每个变量分配类型:
Dim countFiles as Integer, countSheets As Integer