-3

我真正想做的就是将源范围中每一列的条件格式复制到数据透视表上的相应列中。它越来越近了,但现在我在尝试应用格式时收到错误 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
4

1 回答 1

3

正如您所怀疑的,这与您上一个问题中的问题完全相同,但还有一些问题需要解决。如果您打算在未来进行任何重要的 Excel VBA 开发,您绝对应该花时间学习可以用来避免.Select.

或者,您可以在修改之前简单地选择数据透视表工作表。请注意,这不是最佳实践,但可以让您的代码运行。

在您的“错误!评论:

ws.Select

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

您无法使用您正在使用的语法选择范围。代替

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

你需要

ws.Cells(5, intCntrCol).Select
于 2013-05-02T12:48:22.293 回答