代码之家  ›  专栏  ›  技术社区  ›  Dan

Excel VBA:更新数据透视源数据

  •  0
  • Dan  · 技术社区  · 15 年前

    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;") _
        )
    

    但这甚至不允许我指定要更新哪个透视表。。。或者甚至做我真正想做的事情,即更新数据透视缓存,以便更新使用相同源的所有数据透视表。

    那么,更新sourcedata的好方法是什么呢?

    编辑:

    但我甚至得到了“应用程序定义的或对象定义的错误”错误,原因很简单:

    str = Sheets("Totals").PivotTables("PivotTable2").PivotCache.CommandText
    Sheets("Totals").PivotTables("PivotTable2").PivotCache.CommandText = str
    

    我再次检查了我的数据透视表是否仍在访问实时数据,并刷新它是否仍然有效。。。但是我无法将命令字符串设置为当前的值?真奇怪。

    谢谢

    1 回复  |  直到 6 年前
        1
  •  6
  •   marg    15 年前

    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
    

    您可以访问要编辑的连接:

    ThisWorkbook.PivotCaches(yourIndex).Connection
    

    注意:更改连接后,您应呼叫:

    ThisWorkbook.PivotCaches(yourIndex).Refresh
    

    编辑: 您可以更改CommandText,而不是更改SourceData。这应该有同样的效果。以下代码适用于我:

    ThisWorkbook.PivotCaches(1).CommandText = "SELECT movies.title, movies.rating, movies.comments FROM `C:\Folder\moviesDB`.movies movies"
    ThisWorkbook.PivotCaches(1).Refresh
    

    这段代码还更新了我的SourceData。

    编辑2:

    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
    

    注意:moviesDB是一个.mdb文件,movies是表/查询

    注2:这也可能有助于您 Debug.Print 更改工作命令之前,请先删除该文本。这将为您的新CommandText提供一个模板。

    推荐文章