我正在excel中使用vba进行开发,并想要创建一些excelsheet来呈现数据透视表和图表。
我用从自定义mdx查询返回的记录集做到了这一点。下面有一个示例,该示例将数据从多维数据集返回到记录集,然后创建数据透视表和图表。像魅力一样工作。
Public Sub CreatePivotTableAndChart()
Dim MDXQuery As String
'Declare variables
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
On Error GoTo ErrorHandler
'Open Connection
conn.ConnectionString = "Provider=MSOLAP.7;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=xxxxxxx;Data Source=xxxxxxxx;MDX Compatibility=1;Safety Options=2;Protocol Format=XML;MDX Missing Member Mode=Error;Packet Size=32767"
conn.Open
'Custom MDX query
MDXQuery = "WITH" & vbCrLf & _
"MEMBER [Measures].[DateValue] AS [DT_dTime].[Date].MemberValue" & vbCrLf & _
"SELECT {[Measures].[DT_mTransactions_Count], [Measures].[DateValue]} ON COLUMNS," & vbCrLf & _
"(Filter([DT_dTime].[Date].[Date].ALLMEMBERS, [Measures].[DT_mTransactions_Count] > 0)) ON ROWS" & vbCrLf & _
"FROM ( SELECT ( { [DT_dTags_Gender].[ParentTagID].&[4061],[DT_dTags_Gender].[ParentTagID].&[4062] } ) ON COLUMNS" & vbCrLf & _
"FROM [DT_BizTrackCube])" & vbCrLf & _
"WHERE ([DT_dTime].[Month].&[2018-01-01T00:00:00], [DT_dTags_MeasureType].[ParentTagID].&[8])"
rs.Open MDXQuery, conn
'Create new pivot cache
Set ws = ThisWorkbook.Worksheets("TestPivotTable")
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlExternal)
rs.MoveFirst
'Set recordset
Set pc.Recordset = rs
'Create new pivot table
Set pt = pc.CreatePivotTable(TableDestination:=ws.Range("A1"), TableName:="PivotTable")
'define pivotfields
pt.PivotFields("[Measures].[DateValue]").Orientation = xlRowField
pt.PivotFields("[Measures].[DT_mTransactions_Count]").Orientation = xlDataField
pt.ManualUpdate = False
'Create new pivot chart
Dim objShape As Shape
ActiveSheet.PivotTables("PivotTable").PivotSelect "", xlDataAndLabel, True
Set objShape = ActiveSheet.Shapes.AddChart2(227, xlLine)
With objShape
.Select
'Name formatting, position
.Name = "PivotChart"
.Left = Range("E1").Left
.Top = Range("E1").Top
.Width = 646
.Height = 300
'Titles
.chart.HasTitle = True
.chart.ChartTitle.Text = "Maand vergelijking"
.chart.Axes(xlCategory, xlPrimary).HasTitle = True
.chart.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Dagen"
.chart.Axes(xlValue, xlPrimary).HasTitle = True
.chart.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Leads"
End With
'Close recordset
rs.Close
'Reset recordset
Set rs = Nothing
'Close connection
conn.Close
'Reset connection
Set conn = Nothing
Done:
Exit Sub 'Exit to avoid error handler
ErrorHandler:
Debug.Print "ErrorHandler"
' Get VB Error Object's information
strTmp = "VB Error # " & Str(Err.Number)
strTmp = strTmp & vbCrLf & " Generated by " & Err.Source
strTmp = strTmp & vbCrLf & " Description " & Err.Description & vbCrLf
Debug.Print strTmp
End Sub
唯一的问题是此解决方案使我的结果变平了。我想例如使用带有交叉联接的mdx查询,以便可以使用行分组(维度)。结果是多维结果。 我知道该多维数据集返回一个单元集,但是如何从一个单元集创建数据透视表?那有可能吗?我找到了一些示例,这些示例说明了如何读取单元集并将结果打印到平面表,但是 不是一个如何从中创建数据透视表的方法。
希望您能帮助我。提前致谢。