寻找更为合适的方式。虽然我有一个可行的解决方案,但它似乎应该有一个内置或更优雅的方法。
我正在比较来自不同工作簿的两个工作表,在当前工作簿的一张工作表中记录差异。每当发现差异时,我就会生成一行输出数据。由于我不知道将找到的差异总数,因此输出数据的行会附加到ArrayList中。
我有一个可用的代码,但是它的有效方法是:
- 将一行创建为ArrayList。
- 将该行转换为数组。
- 将该行添加到用于输出的ArrayList中
- 将输出ArrayList两次转置并转换为数组
- 将数组输出到工作表。
尽管使用ArrayLists有诸多好处,但似乎应该有直接输出2D“ArrayList of ArrayLists”或类似内容的方法。
以下是当前的代码:
Sub findUnmatchingCells()
Dim oWB_v1 As Workbook, oWB_v2 As Workbook, oRange_v1 As Range, oRange_v2 As Range
On Error GoTo endofsub
With Me
.Cells.Clear
.Cells(1, 1) = "Row"
.Cells(1, 2) = "Column"
.Cells(1, 3) = "v1"
.Cells(1, 4) = "v2"
End With
Dim missing_items As Object
Dim output_row(), output(), missing_row As Object
Set oWB_v1 = Workbooks("foo.xls")
Set oWB_v2 = Workbooks("bar.xls")
Set oRange_v1 = oWB_v1.Sheets(1).Range("A1:AD102")
Set oRange_v2 = oWB_v2.Sheets(1).Range("A1:AD102")
Set missing_items = CreateObject("System.Collections.ArrayList")
For rRow = 1 To oRange_v1.Rows.Count
For cCol = 1 To oRange_v1.Columns.Count
If oRange_v1.Cells(rRow, cCol) <> oRange_v2.Cells(rRow, cCol) Then
Set missing_row = CreateObject("System.Collections.ArrayList")
missing_row.Add rRow
missing_row.Add cCol
missing_row.Add oRange_v1.Cells(rRow, cCol).Value2
missing_row.Add oRange_v2.Cells(rRow, cCol).Value2
output_row = missing_row.toarray
missing_items.Add output_row
End If
Next cCol
Next rRow
output = Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Transpose(missing_items.toarray))
'my own output routine
If Not outputArrayToRange(output, Me.Range("A2")) Then Stop
Exit Sub
endofsub:
Debug.Print rRow, cCol, missing_items.Count, missing_row.Count, Error
Stop
End Sub