我想创建一个宏来比较报告的两个版本,以便在创建新报告时检查历史数据是否已更改。
我想遍历一张工作表的Used Range,然后将该范围内的每个单元格与另一张工作表中的相同地址进行比较。
这是到目前为止的代码:
Sub Compare_Report()
Dim vRange As Range
Dim v_Rangeversie As Range
On Error GoTo ErrorCatch
Debug.Print Now
Set v_Rangeversie = Worksheets("VorigeVersie").UsedRange
For Each v_range In Worksheets("1. Overzicht").UsedRange
For Each vCell In v_range
Debug.Print vCell.Address
'If vCell.Value != v_Rangeversie.Range.Cell(vCell.address)
'Then
' Debug.Print "Ongelijk"
' Cells are different.
' varSheetB.Cell.Interior.ColorIndex = 3
' varSheetB.Cell.Font.Color = 2
'End If
Next
Next
Exit Sub
ErrorCatch:
MsgBox Err.Description
End Sub
我无法让这个If语句起作用:
'If vCell.Value != v_Rangeversie.Range.Cell(vCell.address)
我想念什么?请帮忙。
问候,Jan
答案 0 :(得分:3)
这样的事情:
Sub compareSheets(shtBefore As String, shtAfter As String)
'Retrieved from MrExcel.Com July 2012
Dim mycell As Range
Dim mydiffs As Integer
For Each mycell In ActiveWorkbook.Worksheets(shtAfter).UsedRange
If Not mycell.Value = _
ActiveWorkbook.Worksheets(shtBefore).Cells(mycell.Row, mycell.Column).Value Then
'Or use "mycell.Value <> othercell.Value"
mycell.Interior.Color = vbYellow
mydiffs = mydiffs + 1
End If
Next
MsgBox mydiffs & " differences found", vbInformation
ActiveWorkbook.Sheets(shtAfter).Select
End Sub
它突出了黄色的差异。
使用它时,你应该在另一个sub中调用它:
Sub highlight_differences()
Call compareSheets("1. Overzicht", "VorigeVersie")
End Sub
答案 1 :(得分:1)
条件格式替代方案。您可能希望在VBA中编写它以便在生成报告后调用它...这是一个单行:
Worksheets("1. Overzicht").UsedRange.FormatConditions.Add _
(xlExpression, , "=A1<>VorigeVersie!A1").Interior.ColorIndex = 3