我知道以前有人问过这个问题,但在这个具体情况下没有。 我已经用 GPT 4o 尝试了大约一个小时。
我使用以下测试Excel:一张带有小表格的工作表作为测试数据。
当我执行下面的代码时,出现标题中提到的错误。
Sub debugger()
'Select the file to finish the Pivot table
Dim currentFolder As String
currentFolder = ThisWorkbook.Path
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.InitialFileName = currentFolder & "\"
fd.Show
'Extract file path and file name
Dim selectedFilePath As String
Dim selectedFileName As String
selectedFilePath = fd.SelectedItems(1)
selectedFileName = Dir(selectedFilePath)
'Open new copy workbook and adjust the data
With Workbooks.Open(selectedFilePath)
'Create the Pivot
Dim wb As Workbook
Dim Ws As Worksheet
Dim NewSheet As Worksheet
Dim PivotCache As PivotCache
Dim PivotTable As PivotTable
Dim conn As WorkbookConnection
Dim Rng As Range
Dim ConnName As String
Dim TestPath As String
Set Ws = .Worksheets(1)
Set Rng = Ws.UsedRange
'Create a new sheet for the PivotTable
Set NewSheet = .Worksheets.Add(Before:=Ws)
NewSheet.Name = "testpivot"
'Add the UsedRange to the Data Model by creating a WorkbookConnection
ConnName = "DataModelConnection"
On Error Resume Next 'Ignore if connection already exists
Set conn = wb.Connections(ConnName)
On Error GoTo 0
If conn Is Nothing Then
Set conn = .Connections.Add2(Name:=ConnName, _
Description:="Connection to worksheet data", _
connectionString:="WORKSHEET;" & .FullName, _
CommandText:=Rng.Address(External:=True), _
lCmdtype:=xlCmdExcel)
End If
'Now create a PivotCache from the Data Model (external connection)
Set PivotCache = .PivotCaches.Create(SourceType:=xlExternal, SourceData:=conn, Version:=xlPivotTableVersion15)
'Create the PivotTable from the data model connection
Set PivotTable = PivotCache.CreatePivotTable( _
TableDestination:=NewSheet.Cells(1, 1), _
TableName:="testpivot", _
DefaultVersion:=xlPivotTableVersion15)
Ws.Activate
With PivotTable
'Add a field to the Filters area
.PivotFields("Testfield1").Orientation = xlPageField
.PivotFields("Testfield1").Position = 1
End With
End With
End Sub
具体来说这段代码:
With PivotTable
'Add a field to the Filters area
.PivotFields("Testfield1").Orientation = xlPageField
.PivotFields("Testfield1").Position = 1
End With
我录制了一个宏来查看如何添加字段。 看来它实际上是
CubeFields
这里是重构为使用 OP 的 PivotTable
变量的宏。 我建议记录您按照您想要的方式设置表格的宏,然后让 ChatGPT 为您重构它。
With PivotTable.CubeFields("[Range 3].[Testfield1]")
.Orientation = xlRowField
.Position = 1
End With
With PivotTable.CubeFields("[Range 3].[Testfield2]")
.Orientation = xlColumnField
.Position = 1
End With
With PivotTable.CubeFields("[Range 3].[Testfield3]")
.Orientation = xlColumnField
.Position = 2
End With