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