无法在VBA中的新工作表中创建透视

时间:2017-09-13 08:57:35

标签: vba excel-vba excel

我录制了一个宏,我想在其中创建一个数据透视表到新工作表中。我正在使用2010版。

我有“运行时错误5”无效的过程调用或参数“当我想运行一个宏时出错。请查看代码。它会创建新的表单,所以它不是很好吗?

Range("A1").Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R1C1:R17445C24", Version:=xlPivotTableVersion12).CreatePivotTable _
TableDestination:="Sheet4!R3C1", TableName:="PivotTable1", DefaultVersion _
:=xlPivotTableVersion12

Sheets("Sheet4").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Bnlunit")
    .Orientation = xlPageField
    .Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Period")
    .Orientation = xlColumnField
    .Position = 1
End With
ActiveWindow.SmallScroll Down:=12
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Amount"), "Sum of Amount", xlSum
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Hdaccount_agr_3(T)")
    .Orientation = xlRowField
    .Position = 1
End With
ActiveWindow.SmallScroll Down:=-33

End Sub

2 个答案:

答案 0 :(得分:0)

问题是由于工作表名称而没有删除这些工作表。我认为以下代码可能是您的帮助

Sub Macro1()
'
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long

'Delete Preivous Pivot Table Worksheet & Insert a New Blank Worksheet With Same Name
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Raw Data")

'Define Data Range
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)

'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="PRIMEPivotTable")

'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable_(TableDestination:=PSheet.Cells(1, 1), TableName:="PRIMEPivotTable")

'Insert Column Fields
'With ActiveSheet.PivotTables("PRIMEPivotTable").PivotFields("ColumnName")
 '.Orientation = xlColumnField
 '.Position = 1
'End With

'Insert Row Fields
With ActiveSheet.PivotTables("PRIMEPivotTable").PivotFields("RowName")
 .Orientation = xlRowField
 .Position = 1
End With

'Insert Data Field
With ActiveSheet.PivotTables("PRIMEPivotTable").PivotFields("Field 1")
 .Orientation = xlDataField
 .Position = 1
 .Function = xlCount
 .Name = "Name of your choice"
End With


End Sub

答案 1 :(得分:0)

尝试下面的代码,代码注释中的解释:

UPDATE mysql.user SET user='newusername',
password=PASSWORD('newpassword') WHERE user='root';
FLUSH PRIVILEGES;