我试图从两个工作簿的行范围中复制一定范围的单元格。此信息用于按ID比较两个工作簿行的内容。
我尝试的第一个解决方案涉及逐个单元的“二进制”比较。这适用于几行工作表:
For i = 2 To LastSheetRow
Set FoundCell = Workbooks(WorkbookA).Sheets(SheetNameFromArray).Range("A:A").Find(What:=Workbooks(WorkbookB).Sheets(SheetNameFromArray).Cells(i, 1).Value)
If Not FoundCell Is Nothing Then
aCellValues(0) = 1
Workbooks(UserWorkbook).Sheets(SheetNameFromArray).Cells(i, LastSheetColumn + 1).Value = FoundCell.Row
For j = 2 To LastSheetColumn
Select Case Workbooks(WorkbookB).Sheets(SheetNameFromArray).Cells(i, j).Value
Case Is = Workbooks(WorkbookA).Sheets(SheetNameFromArray).Cells(FoundCell.Row, j).Value
aCellValues(j - 1) = 1
Case Else
aCellValues(j - 1) = 0
End Select
Next j
Else
End If
Next i
我想将两个工作簿中每行的一行的内容存储在一个数组中以进行比较,因为我认为这是一种更快的解决方案。
定义范围进行比较后,将单元格复制到数组中时遇到以下错误:
子索引超出间隔(错误9)
这会产生错误:
Dim aWorkbookBInfo() As Variant, aWorkbookAInfo() As Variant, rngWorkbookBToCompare As Range, rngWorkbookAToCompare As Range
Dim SumToCheck As Integer, FoundCell As Range, aCellValues() As Integer
ReDim aCellValues(LastSheetColumn - 1)
ReDim aWorkbookBInfo(LastSheetColumn - 1)
ReDim aWorkbookAInfo(LastSheetColumn - 1)
For i = 2 To LastSheetRow
Set FoundCell = Workbooks(WorkbookA).Sheets(SheetNameFromArray).Range("A:A").Find(What:=Workbooks(WorkbookB).Sheets(SheetNameFromArray).Cells(i, 1).Value)
If Not FoundCell Is Nothing Then
aCellValues(0) = 1
Workbooks(WorkbookB).Sheets(SheetNameFromArray).Cells(i, LastSheetColumn + 1).Value = FoundCell.Row
With Workbooks(WorkbookB).Sheets(SheetNameFromArray)
Set rngWorkbookBToCompare = Range(Cells(i, 2), Cells(i, LastSheetColumn))
End With
With Workbooks(WorkbookA).Sheets(SheetNameFromArray)
Set rngWorkbookAToCompare = Range(Cells(FoundCell.Row, 2), Cells(FoundCell.Row, LastSheetColumn))
End With
aWorkbookBInfo = rngWorkbookBToCompare
aWorkbookAInfo = rngWorkbookAToCompare
For j = 1 To LastSheetColumn - 1
If aWorkbookBInfo(j).Value = aWorkbookAInfo(j).Value Then
aCellValues(j) = 1
Else
aCellValues(j) = 0
End If
Next j
Else
End If
Next i
答案 0 :(得分:1)
完整修订版:
范围数组分配在这些行中生成一个二维数组:
aWorkbookBInfo = rngWorkbookBToCompare
aWorkbookAInfo = rngWorkbookAToCompare
无论您在代码开始时如何定义和定义它们的大小,都会发生这种情况。由于它们是二维数组,因此必须将它们寻址为aWorkbookBInfo(a, b)
,其中a
是行,b
是列。
与范围(在任何范围内都可以引用第一个单元格一样)不同,在尝试引用数组项之前,必须完全寻址数组。因此,虽然rngWorkbookBToCompare(j).Value
有效,但aWorkbookBInfo(j).Value
无效。此外, Value 不一定是Excel放入数组中的任何对象的属性。如果要使用列j
的第一个单元格,请尝试添加该行,并忽略对 Value 属性的引用,如下所示:aWorkbookBInfo(1, j)
。