谁能明白为什么这段代码会在最后一行导致 1004 错误?直到最后一行,一切都很好。我让它工作,然后它开始出现这个错误,我不知道为什么。Sheet2 是一张空白纸。Sheet1 目前只是测试数据,10 行 3 列。它从 B3 开始。有人有想法么?
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
' 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
' ActiveWorkbook = The currently opened Workbook
' ActiveSheet = The currectly opened sheet
' UsedRange = The Range of cells with active data in them
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,
' in Excel format,
' placed at the RngTarget location,
' And name it PivotB3 just for reference if needed
ActiveWorkbook.PivotCaches.Create(xlDatabase, RngSource).CreatePivotTable RngTarget, "PivotB3"
' 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
ActiveSheet.PivotTables("PivotB3").PivotSelect "", xlDataAndLabel, True