如何比较两个枢轴之间的数据,如果有任何不匹配,就改变颜色?

我创build了一个macros来为名为“data”的工作表中的数据创build一个数据透视表。 对于“logging”表中的数据也是一样的。 这些表单的内容每次都是可比的。 我想写一个macros来改变单元格的颜色,如果这两个表单中有任何不匹配的话。

在数据表中有50行,logging表中有52行。 那么我想写一个macros,logging表中的两个不匹配的行应该是红色的,rest50应该是绿色的。

任何帮助,将不胜感激。

我的代码:创build枢纽是

Dim bReport As Workbook, Report As Worksheet, pivotSheet As Worksheet Set bReport = Excel.ActiveWorkbook Set Report = bReport.Worksheets("data") Set pivotSheet = bReport.Worksheets.Add Dim pivotSource As Range Set pivotSource = Report.UsedRange 'selecting entire data in the sheet Dim tableName As String tableName = "Pivot_Data" bReport.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=pivotSource).CreatePivotTable _ TableDestination:=pivotSheet.Cells(1, 1), tableName:=tableName Set pt = pivotSheet.PivotTables(tableName) pivotSheet.PivotTableWizard TableDestination:=pivotSheet.Cells(1, 1) Set pOne= pt.PivotFields("Number") Set pTwo = pt.PivotFields("Premium") Set pthree = pt.PivotFields("TransactoinID") Set pFour = pt.PivotFields("money") pOne.Orientation = xlRowField pTwo.Orientation = xlRowField pTwo.Subtotals(1) = False pThree.Orientation = xlRowField pThree.Subtotals(1) = False pFour.Orientation = xlDataField pFour.NumberFormat = "$#,##0.00" 

我也为logging表写了相同的代码。

我尝试了这个代码的颜色变化,但获得对象438错误,如果条件。 这是错误的方法来解决我的问题或任何改善可以发生?

 Sub abc() Dim rCell As Range For Each rCell In Sheet1.Cells 'or Sheet1.Range("A1:D2").Cells If rCell.Value2 <> Sheet2.Range(rCell.AddressLocal).Value2 Then With rCell.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = 65535 'YELLOW, make this the color of your choice .TintAndShade = 0 .PatternTintAndShade = 0 End With With Sheet2.Range(rCell.AddressLocal).Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = 65500 'YELLOW, make this the color of your choice .TintAndShade = 0 .PatternTintAndShade = 0 End With End If Next rCell End Sub 

您可以使用条件格式或脚本比较:

条件格式将继续检查差异,您可以将条件格式应用于一个或两个工作表,并在不等于设置背景颜色时,只引用另一个工作表上的同一个单元格。 为了使这个最简单,只需要在1中应用相同的条件格式,就可以进入整个单元格范围(甚至可以是整个表单),并为左上angular的单元格设置比较(取出美元符号以使格式公式沿着与成员单元格)

脚本化的比较将需要你申请一小块VBA代码,例如迭代所有的单元格(其他可能有更优雅/高效的解决scheme),像这样(未经testing):

 Dim rCell as Range For each rCell in Sheet1.Range("A1:D2").Cells 'Or Sheet1.Cells If rCell.Value2 <> Sheet2.Range(rCell.AddressLocal).Value2 Then With rCell.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = 65535 'YELLOW, make this the color of your choice .TintAndShade = 0 .PatternTintAndShade = 0 End With With Sheet2.Range(rCell.AddressLocal).Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = 65535 'YELLOW, make this the color of your choice .TintAndShade = 0 .PatternTintAndShade = 0 End With End If Next rCell