【发布时间】:2021-10-19 04:05:13
【问题描述】:
我有多个 Excel 工作簿,其中一些有多个工作表。
我正在尝试使用每个工作簿的 A 列作为唯一值,将工作簿中的重复项导出到新工作簿中。所有工作簿都在同一个目录中。
我想出了以下方法,但它似乎不适用于具有多个工作表的工作簿,并且对于某些工作簿也不准确。
Sub CheckDuplicateAcrossWorkbook()
Dim fName As String, fPath As String, wb As Workbook, sh As Worksheet, i As Long
Set sh = ActiveSheet
fPath = ThisWorkbook.Path & "\"
fName = Dir(fPath & "*.xls*")
Do
If fName <> ThisWorkbook.Name Then
Set wb = Workbooks.Open(fPath & fName)
If sh.Range("B1") = "" Then
sh.Range("A1") = "Source"
End If
wb.Sheets(1).UsedRange.Offset(1).Copy sh.Cells(Rows.Count, 2).End(xlUp)(2)
With sh
.Range(.Cells(Rows.Count, 1).End(xlUp)(2), .Cells(Rows.Count, 2).End(xlUp).Offset(, -1)) = fName
End With
wb.Close
End If
Set wb = Nothing
fName = Dir
Loop Until fName = ""
End Sub
```
The original code which removes the first five rows and 8th row with the header being row 7.
```vba
Sub CheckDuplicateAcrossWorkbookOriginal()
Dim fName As String, fPath As String, wb As Workbook, sh As Worksheet, i As Long
Set sh = ActiveSheet
fPath = ThisWorkbook.Path & "\"
fName = Dir(fPath & "*.xls*")
Do
If fName <> ThisWorkbook.Name Then
Set wb = Workbooks.Open(fPath & fName)
If sh.Range("B1") = "" Then
wb.Sheets(1).Range("A7", Sheets(1).Cells(7, Columns.Count).End(xlToLeft)).Copy sh.Range("B1")
sh.Range("A1") = "Source"
End If
wb.Sheets(1).UsedRange.Offset(8).Copy sh.Cells(Rows.Count, 2).End(xlUp)(2)
With sh
.Range(.Cells(Rows.Count, 1).End(xlUp)(2), .Cells(Rows.Count, 2).End(xlUp).Offset(, -1)) = fName
End With
wb.Close
End If
Set wb = Nothing
fName = Dir
Loop Until fName = ""
For i = sh.UsedRange.Rows.Count To 2 Step -1
If Application.CountIf(sh.Range("B:B"), sh.Cells(i, 2).Value) = 1 Then Rows(i).Delete
Next
End Sub
【问题讨论】: