Jea*_*ett 26
难道不是遍历所有的细胞!工作表和VBA之间的通信有很多开销,用于读写.循环通过所有细胞将是痛苦的缓慢.我在说几个小时.
而是将整个工作表一次加载到Variant数组中.在Excel 2003中,这需要大约2秒(和250 MB的RAM).然后你可以立刻循环它.
在Excel 2007及更高版本中,工作表大约大1000倍(1048576行×16384列= 170 亿个单元,而Excel36中为65536行×256列= 1700 万).如果您尝试将整个工作表加载到Variant中,则会遇到"Out of memory"错误; 在我的机器上,我一次只能加载3200万个单元格.因此,您必须将自己限制在您知道其中包含实际数据的范围内,或逐位加载工作表,例如一次加载30列.
Option Explicit
Sub test()
Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
strRangeToCheck = "A1:IV65536"
' If you know the data will only be in a smaller range, reduce the size of the ranges above.
Debug.Print Now
varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
Debug.Print Now
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
' Cells are identical.
' Do nothing.
Else
' Cells are different.
' Code goes here for whatever it is you want to do.
End If
Next iCol
Next iRow
End Sub
Run Code Online (Sandbox Code Playgroud)
要与不同工作簿中的工作表进行比较,请打开该工作簿并获取工作表,如下所示:
Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need
Run Code Online (Sandbox Code Playgroud)