你的
MsgBox
包含太多
String
MsgBox difference & " cells contain different data! ", vbInformation, "Comparing Two Worksheets cells contain different data"
除此之外,您的产品线:
If colval <> colval2 Then
应该是:
If colval1 <> colval2 Then
此外,尽量不要使用
Row
iRow
相反(或任何其他)。
尝试以下代码(代码注释中的解释):
Dim wsResult As Worksheet
Set report = Workbooks.Add
Set wsResult = report.Worksheets(1) ' <-- set the worksheet object
With ws1.UsedRange
ws1row = .Rows.Count
ws1col = .Columns.Count '<-- had an error here (was `ws2col`)
End With
With ws2.UsedRange
ws2row = .Rows.Count
ws2col = .Columns.Count
End With
' Use Max function
maxrow = WorksheetFunction.Max(ws1row, ws2row)
maxcol = WorksheetFunction.Max(ws1col, ws2col)
'maxrow = ws1row
'maxcol = ws1col
'If maxrow < ws2row Then maxrow = ws2row
'If maxcol < ws2col Then maxcol = ws2col
difference = 0
For col = 1 To maxcol
For iRow = 1 To maxrow
colval1 = ""
colval2 = ""
colval1 = ws1.Cells(iRow, col).Formula
colval2 = ws2.Cells(iRow, col).Formula ' <-- you had an error here, you used `colval1 = ws1.Cells(Row, col).Formula`
If colval1 <> colval2 Then '<-- you had an error here (used `If colval <> colval2`)
difference = difference + 1
' don't rely on ActiveSheet, use the wsResult worksheet object
wsResult.Cells(iRow, col).Formula = colval1 & "<>" & colval2
wsResult.Cells(iRow, col).Interior.Color = 255
wsResult.Cells(iRow, col).Font.ColorIndex = 2
wsResult.Cells(iRow, col).Font.Bold = True
End If
Next iRow
Next col
wsResult.Columns("A:B").ColumnWidth = 25
report.Saved = True
If difference = 0 Then
report.Close False
End If
Set report = Nothing
MsgBox difference & " cells contain different data! ", vbInformation, "Comparing Two Worksheets cells contain different data"