2

我创建了一个宏来为名为"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
4

1 回答 1

1

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

条件格式将继续检查差异,您可以将条件格式应用于一张或两张纸,当设置背景颜色不相等时,只需引用另一张纸上的相同单元格。为了使这最简单,只需在 1 中应用相同的条件格式,转到整个单元格范围(甚至可能是完整的工作表),并为最左上角的单元格设置比较(取出美元符号以使格式公式继续移动与成员细胞)

脚本比较将需要您应用一小段 VBA 代码,例如在其中迭代所有单元格(其他可能有更优雅/高效的解决方案),如下所示(未经测试):

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
于 2013-04-30T10:31:42.713 回答