TCD数据透视表ADODB访问

时间:2018-06-25 22:03:26

标签: excel-vba pivot-table vba excel

我声明了常量变量的模块

Public Const ADODB_PROVIDER = "OLEDB;Provider=Microsoft.ACE.OLEDB.12.0;"
Public Const PATH_DB = "E:\BkUpData\Projets\Access\GarageHellMotors\facturation_be_test.accdb"

在另一个模块中,此功能在工作簿加载事件上调用

Public Function fWkBookCnxAdd()

Dim objWBConnect As WorkbookConnection

Set objWBConnect = ThisWorkbook.Connections.Add( _
Name:="tcd", Description:="", _
ConnectionString:=ADODB_PROVIDER & _
"Data Source=" & PATH_DB, _
CommandText:="SELECT * FROM qryFactureSumMonthYear", _
lCmdtype:=xlCmdSql)

End Function

请参见l enter link description here

在选项卡上,我在点击时添加了一个带有以下代码的commandButton

Private Sub cmdTcd_Click()

Dim oPivotCache As PivotCache
Dim oPtTable As PivotTable

ActiveSheet.Range("A3").CurrentRegion.Clear 

' Create a PivotTable cache
Set oPivotCache = ActiveWorkbook.PivotCaches.Add(SourceType:=xlExternal,  _
SourceData:=ThisWorkbook.Connections(1))

Set oPtTable = oPivotCache.CreatePivotTable( _ 
TableDestination:=Range("A3"), _
TableName:="tcd") 

但是下面的这段代码是错误的,我不知道在哪里

  

设置oPivotCache = ActiveWorkbook.PivotCaches.Add(SourceType:= xlExternal,_       SourceData:= ThisWorkbook.Connections(1))

所以下面的命令会生成应用程序定义的错误或对象定义的错误'1004'

  

设置oPtTable = oPivotCache.CreatePivotTable(_       TableDestination:= Range(“ A3”),_       TableName:=“ tcd”)'--->错误1004       ...代码

预先感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我在下面找到了这个解决方案

在模块中

Public Const ADODB_PROVIDER = "OLEDB;Provider=Microsoft.ACE.OLEDB.12.0;"
Public Const PATH_DB = "E:\Access\test.accdb"

Public Function fWkBookCnxDelAll()
Dim oWkBookCnx As WorkbookConnection

For Each oWkBookCnx In ThisWorkbook.Connections
    oWkBookCnx.Delete
Next oWkBookCnx
End Function

Public Function fWkBookCnxInitAll()    
Dim objWBConnect As WorkbookConnection

Set objWBConnect = ThisWorkbook.Connections.Add( _
Name:="tcd", Description:="", _
ConnectionString:=ADODB_PROVIDER & _
"Data Source=" & PATH_DB, _
CommandText:="SELECT * FROM qryFactureSumMonthYear", _
lCmdtype:=xlCmdSql)
End Function

在Thisworkbook加载事件中,下面的代码

Private Sub Workbook_Open()
 fWkBookCnxDelAll
 fWkBookCnxInitAll    
End Sub

在工作表的命令按钮单击事件上,下面的代码

Private Sub cmdAddTCD_Click()

Dim oCnx As WorkbookConnection
Dim oPc As PivotCache
Dim oPt As PivotTable

ActiveSheet.Range("G7").CurrentRegion.Clear '

' Create a PivotTable cache
Set oCnx = ThisWorkbook.Connections("tcd")
Set oPc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlExternal, _
SourceData:=oCnx)

' Create a tcd.
Set oPt = oPc.CreatePivotTable( _
TableDestination:=ActiveSheet.Range("G4"), _
TableName:="tcd")

With oPt
    .SmallGrid = False

    .AddFields _
    RowFields:="idfacture", _
    RowFields:="libelle", _
    ColumnFields:="PeriodemontYear"

    .AddDataField _
    Field:=oPt.PivotFields("montant") _
 End With
End Sub

现在创建了一个新的TCD