尝试将条件格式复制到pivottable

时间:2013-05-02 12:20:50

标签: excel vba excel-vba

我真正想做的就是将条件格式从源范围中的每一列复制到pivottable上的相应列。它越来越近了,但现在我在尝试应用格式时遇到错误1004。这是代码:

    Sub CreatePivot()
        ' Define RngTarget and RngSource as Range type variables
        Dim RngTarget As Range
        Dim RngSource As Range
        Dim intLastCol As Integer
        Dim intCntrCol As Integer
        Dim ws As Worksheet
        Dim pt As PivotTable

        Set ws = ThisWorkbook.Sheets("Sheet2")
        ws.Cells.Clear

        ' RngTarget is where the PivotTable will be created (ie: Sheet2, Cell B3)
        Set RngTarget = ThisWorkbook.Worksheets("Sheet2").Range("B3")

        ' RngSource defines the Range that will be used to create the PivotTable
        Set RngSource = ActiveWorkbook.ActiveSheet.UsedRange

        ' Select the Range
        RngSource.Select

        ' Copy the Range into the clipboard
        RngSource.Copy

        ' Create a new PivotTable using the RngSource defined above
        ActiveWorkbook.PivotCaches.Create(xlDatabase, RngSource).CreatePivotTable RngTarget, "PivotB3"
        Set pt = RngTarget.PivotTable

        ' Get the last used column from the data table
        intLastCol = RngSource.Columns(RngSource.Columns.Count).Column

        ' Select the Pivot table so we can apply the conditional formats
        pt.PivotSelect "", xlDataAndLabel, True

        ' ERROR! Error when "ws.Range(Cells(5, intCtrCol)).Select" is first called
        For intCntrCol = 3 To intLastCol
            ws.Range(Cells(5, intCtrCol)).Select ' Select the current Sum column
            Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, Formula1:="=5000" ' Set conditional format to less than 5000
            Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority ' Take priority over any other formats
            With Selection.FormatConditions(1).Font ' Use the Font property for the next operations
                .ThemeColor = xlThemeColorLight1 ' Set it to the default (if it does not meet the condition)
                .TintAndShade = 0 ' Same as above
            End With
            With Selection.FormatConditions(1).Interior
                .PatternColorIndex = xlAutomatic
                .Color = 65535 ' Set the background color to Yellow
                .TintAndShade = 0
            End With
            Selection.FormatConditions(1).StopIfTrue = False
            Selection.FormatConditions(1).ScopeType = xlFieldsScope ' Apply the format to all rows that match "Sum of xxxx"
        Next intCntrCol
    End Sub

1 个答案:

答案 0 :(得分:3)

这与你上一期的问题完全相同,正如你所怀疑的那样,但还有一些问题需要修复。如果您将要进行任何重要的Excel VBA开发,您绝对应该花时间学习可以用来避免.Select的模式。

或者,您可以在修改之前简单地选择数据透视表。请注意,这不是最佳做法,但会允许您的代码运行。

在“错误”上方添加此行!评价:

ws.Select

你在for循环的第一行拼错了变量名。该计数器名为intCntrCol,您将其称为intCtrCol。养成在工作时编译代码的习惯,你永远不会遇到这些错误。 调试 - >编译

您无法使用所使用的语法选择范围。而不是

ws.Range(Cells(5, intCtrCol)).Select

你需要

ws.Cells(5, intCntrCol).Select