【发布时间】:2014-12-27 10:34:08
【问题描述】:
我正在从一个从 adodb 连接导入其记录集的数据透视缓存创建自动数据透视表。
我需要对日期字段进行分组,并在网上找到了一种使用 .pivotselect 方法的方法。代码工作正常,但是即使选择了数据透视表,excel 似乎也没有选择数据透视表所在的工作表。如果选择另一张纸然后运行该过程,这会导致错误。
pivottable.pivotselect 不应该也自动选择工作表吗?我已经通过在日期分组代码之前使用 sheet("Pivot").select 暂时解决了这个问题。如何解决这个问题?当前代码基于宏记录器生成的代码。
代码
Private Sub PivotAccessADODB()
' Link Pivottable to access database, successfull!
Const ConnectionPath As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\name\Desktop\DataBase.accdb;Persist Security Info=False;"
Dim DataConnection As ADODB.Connection: Set DataConnection = New ADODB.Connection
Dim RecordSet As ADODB.RecordSet: Set RecordSet = New ADODB.RecordSet
DataConnection.ConnectionString = ConnectionPath
DataConnection.Open
Dim SQLString As String: SQLString = "SELECT * FROM ALFA"
With RecordSet
.ActiveConnection = DataConnection
.Source = SQLString
.LockType = adLockReadOnly
.CursorType = adOpenForwardOnly
.Open
End With
' Initiate accept of external data
Dim PTCache As PivotCache
Set PTCache = ActiveWorkbook.PivotCaches.Create(xlExternal)
Set PTCache.RecordSet = RecordSet
'----------------------------------'
'First Pivot Table export procedure
Dim PT As PivotTable: Set PT = PTCache.CreatePivotTable(Sheets("Pivot").Range("A1"), "PivotTable#1")
With PT
.PivotFields("Date").Orientation = xlRowField
.PivotFields("Date").Position = 1
Sheets("pivot").Select ' Bypass selection grouping error, temporary solution as of 2014-12-26
PT.PivotSelect "Date[All]", xlLabelOnly + xlFirstRow, True
Selection.Group Start:=True, End:=True, Periods:=Array(False, False, False, False, True, False, False)
.PivotFields("Adj Close").Orientation = xlDataField
.PivotFields("Sum of Adj Close").Calculation = xlPercentDifferenceFrom
.PivotFields("Sum of Adj Close").BaseItem = "(previous)"
.PivotFields("Volume").Orientation = xlDataField
.PivotFields("Sum of Volume").Calculation = xlPercentDifferenceFrom
.PivotFields("Sum of Volume").BaseItem = "(previous)"
End With
Dim wst As Worksheet: Set wst = Sheets("Mainwindow")
Dim wshape As Shape
Set wshape = wst.Shapes.AddChart2(286, xl3DColumnClustered, wst.Range("A24").Left, wst.Range("A24").Top, _
wst.Range("A24:Q24").Width, wst.Range("A24:A39").Height)
With wshape.Chart
.SetSourceData Source:=PT.TableRange1
.ClearToMatchStyle
.ChartStyle = 291
.ApplyLayout (1)
.ChartTitle.Text = "Difference from previous month in percentage"
.ChartTitle.Format.TextFrame2.TextRange.Font.Size = 14
End With
'-----------------------------------'
'Second Pivot Table export procedure'
'Cleanup
RecordSet.Close
DataConnection.Close
Set RecordSet = Nothing
Set DataConnection = Nothing
End Sub
【问题讨论】:
-
您是否尝试过在查看 Locals 窗口的同时逐行执行代码进行调试?这条线是问题'Sheets("pivot").Select'吗?
-
只需创建一个 Woksheet 变量,将 ThisWorkbook.Sheets("Pivot") 分配给它并将其用作您的 WorkSheet 参考。
-
"Sheets("Pivot").select 只是防止错误的临时解决方案。我已逐步执行代码,代码在"Sheets("Pivot" ).select 如果在运行代码时没有选择该工作表。
-
我试过你的建议很酷的蓝色,但仍然出现同样的错误。