Dan*_*Dan 0 database excel vba pivot excel-vba
我试着记录代码来更新一个pivot sourcedata,它给了我这个:
ActiveSheet.PivotTableWizard SourceType:=xlExternal, _
SourceData:=QueryArry1, _
Connection:=Array( _
Array("ODBC;DSN=MS Access Database;DBQ=" & DBDir & "\" & DBName & ";"), _
Array("DefaultDir=" & DBDir & ";DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;") _
)
Run Code Online (Sandbox Code Playgroud)
但这甚至不允许我指定我想要更新的WHICH数据透视表...甚至做我真正想做的事情,即更新pivotcache以便更新使用相同源的所有数据透视表.
那么更新sourcedata的好方法是什么?
谢谢
编辑:
但我甚至得到了"应用程序定义或对象定义的错误"错误,其中包含以下简单内容:
str = Sheets("Totals").PivotTables("PivotTable2").PivotCache.CommandText
Sheets("Totals").PivotTables("PivotTable2").PivotCache.CommandText = str
Run Code Online (Sandbox Code Playgroud)
我确实仔细检查了我的数据透视表仍在点击实时数据并刷新它仍然有效...但我不能将命令字符串设置为当前的状态?太奇怪了.
谢谢
可以通过工作簿访问数据透视表.您可以使用以下子列表列出所有当前缓存:
Option Explicit
Private Sub listCaches()
Dim selectedCache As PivotCache
For Each selectedCache In ThisWorkbook.PivotCaches
Debug.Print selectedCache.Index
Debug.Print selectedCache.Connection
Next selectedCache
End Sub
Run Code Online (Sandbox Code Playgroud)
您可以使用以下命令访问要编辑的连接:
ThisWorkbook.PivotCaches(yourIndex).Connection
Run Code Online (Sandbox Code Playgroud)
注意:更改连接后,您应该致电:
ThisWorkbook.PivotCaches(yourIndex).Refresh
Run Code Online (Sandbox Code Playgroud)
编辑:您可以更改CommandText,而不是更改SourceData.这应该具有相同的效果.以下代码对我有用:
ThisWorkbook.PivotCaches(1).CommandText = "SELECT movies.title, movies.rating, movies.comments FROM `C:\Folder\moviesDB`.movies movies"
ThisWorkbook.PivotCaches(1).Refresh
Run Code Online (Sandbox Code Playgroud)
此代码还更新了我的SourceData.
Edit2:更改CommandText throgh数据透视表:
Sheets("mySheet").PivotTables("PivotTable1").PivotCache.CommandText = "SELECT movies.title as meh, movies.rating, movies.comments FROM `C:\Folder\moviesDB`.movies movies"
Sheets("mySheet").PivotTables("PivotTable1").PivotCache.Refresh
Run Code Online (Sandbox Code Playgroud)
注意:moviesDB是.mdb文件,电影是表/查询
注意2:Debug.Print在更改之前,它还可以帮助您处理CommandText.这应该为您提供新CommandText的模板.