我想通过比较每个单元格的值来比较vba中的两个excel表单。有没有提高性能的最佳方法?比较两张excel表格的最佳方法是什么?
当我有超过2000到3000行在我的Excel表。它需要大约5分钟执行。有什么办法来优化这个代码?
Sub CompareWorksheets(WS1 As Worksheet, WS2 As Worksheet)
Dim dR As Boolean
Dim r As Long, c As Integer, m As Integer
Dim lrow1 As Long, lrow2 As Long, lrow3 As Long
Dim lcoloumn1 As Integer, lcoloumn2 As Integer,
Dim maxR As Long, maxC As Integer, cf1 As String, cf2 As String
Dim dupCount As Long
With WS1.UsedRange
lrow1 = .Rows.Count
lcoloumn1 = .Columns.Count
End With
With ws2.UsedRange
lrow2 = .Rows.Count
lcoloumn2 = .Columns.Count
End With
maxR = lrow1
maxC = lcoloumn1
If maxR < lrow2 Then maxR = lrow2
If maxC < lcoloumn2 Then maxC = lcoloumn2
DiffCount = 0
lrow3 = 1
For i = 1 To maxR
dR = True
Application.StatusBar = "Comparing worksheets " & Format(i/maxR, "0 %") & "..."
For r = 1 To maxR
For c = 1 To maxC
WS1.Select
cf1 = ""
cf2 = ""
On Error Resume Next
cf1 = WS1.Cells(i, c).FormulaLocal
cf2 = ws2.Cells(r, c).FormulaLocal
On Error GoTo 0
If cf1 <> cf2 Then
dR = False
Exit For
Else
dR = True
End If
Next c
If dR Then
Exit For
End If
Next r
If Not dR Then
dupCount = dupCount + 1
WS1.Range(WS1.Cells(i, 1), WS1.Cells(i, maxC)).Select
Selection.Copy
Worksheets("Sheet3").Select
Worksheets("Sheet3").Range(Worksheets("Sheet3").Cells(lrow3, 1), Worksheets ("Sheet3").Cells(lrow3, maxC)).Select
Selection.PasteSpecial
lrow3 = lrow3 + 1
WS1.Select
For t = 1 To maxC
WS1.Cells(i, t).Interior.ColorIndex = 19
WS1.Cells(i, t).Select
Selection.Font.Bold = True
Next t
End If
Next i
End Sub
谢谢!
显示您到目前为止的代码... –
这就是我如何做的,但我没有它的性能问题。也许,这是你的代码结构的方式,而不是它的问题所在。你可以显示代码,以便我们检查吗? – neelsg