我创建了一个宏来为名为“data”的工作表中的数据创建一个数据透视表。对于表格“记录”中的数据也是如此。这些表的内容每次都是可比的。如果这两张纸不匹配,我想写一个宏来改变单元格的颜色。
在数据表中说有50行,在记录表中有52行。那么我想写一个宏,记录表中两个不匹配的行应该是红色,其余50应该是绿色。
任何帮助将不胜感激。
我的代码:创建支点
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"
我为记录表写的代码也一样。
我尝试使用此代码进行颜色更改,但在If条件下遇到对象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
答案 0 :(得分:1)
您可以使用条件格式或脚本比较:
条件格式将继续检查差异,您可以将条件格式应用于其中一个或两个工作表,并在不相等的设置背景颜色时仅引用另一个工作表上的相同单元格。 为了使这个最简单,只需在1中应用相同的条件格式转到整个单元格区域(甚至可能是完整的单元格),并为最左上角的单元格设置比较(取出美元符号以使格式化公式移动)与成员单元格)
脚本比较将要求您应用一小段VBA代码,例如迭代所有单元格(其他可能有更优雅/高效的解决方案),类似这样(未经测试):< / p>
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