在 VBA 中从 DataModel (Power Pivot) 检索数据

问题描述 投票:0回答:1

首先,抱歉。我是一个相对较新的 VBA 用户,在寻找下面问题的答案时我有点迷失了。

我正在创建一个用户窗体,其中将包含一些组合框来获取用户的输入以查询数据。 我希望从工作簿的 DataModel 中“拉出”这些 ComboBox 的可能值,我在其中加载(仅作为连接)包含可能选项的 Excel 文件。 此类 Excel 按列组织(我需要使用每个组合框一列),其中每一行都是组合框的可能值。

我强烈希望仅将文件作为连接加载(而不是在工作簿工作表之一中创建数据透视表)。

我相信,如果我能够从 DataModel 中的列“提取”每列中的各种值,我可以使用 ComboBox 的 Add.Item 方法。

我遇到的问题:我无法检索 Power Pivot 数据模型中列的值。

Power Pivot 中的数据组织如下:

表名称:src_FieldOptions 第 1 列:门选项(行中可能的值:电动、气动、手动) 第2栏:表面处理(烤漆、光面、哑光)

我尝试使用使用 DataModel 对象的代码(见下文),但即使我能够识别列,我也找不到检索列值(每行)的方法。

您可以提供什么帮助吗? 非常感谢

Sub Find_Values()

    Dim conn As WorkbookConnection
   
    Dim model_Table As modelTable
    Dim model_Column As ModelTableColumn

    ' Set the connection to the Power Pivot Data Model
    Set conn = ThisWorkbook.Connections("Query - src_FieldOptions")
    
    For Each model_Table In conn.ModelTables
       Debug.Print "Table Name: " & model_Table.Name. '<--this is working as expected
       For Each model_Column In model_Table.ModelTableColumns
           Debug.Print "Column Header: " & model_Column.Name & "; " & model_Column.DataType '<-- working as expected

        ' QUESTION FOR YOU ALL: what code should I use here to retrieve the values in the rows of the Data model? 

        Next model_Column
    Next model_Table
       
End Sub
excel vba combobox powerpivot cube
1个回答
0
投票
  • 我在
    ModelTable
    中找不到用于检索数据的
    Object Browser
    对象的任何属性。
  • 有一个解决方案可以使用数据模型检索数据
    ADOConnection
Option Explicit

Sub Find_Value_Demo()
    Dim oConn As WorkbookConnection, oRS As Object ' Recordset
    Dim oCnn As Object, sTabName As String
    ' Set the connection to the Power Pivot Data Model
    Set oConn = ThisWorkbook.Connections("Query - src_FieldOptions")
    ' Set oConn = ThisWorkbook.Connections("Query - Table1") ' for testing
    sTabName = oConn.ModelTables(1).Name ' Assumes there is only one table in DataModel
    Set oCnn = ThisWorkbook.Model.DataModelConnection.ModelConnection.ADOConnection
    Set oRS = CreateObject("ADODB.RecordSet")
    oRS.Open "SELECT * From $" & sTabName & ".$" & sTabName, oCnn
    ' modify as need, to manipulate the data
    Dim i As Long, c As Long
    Sheets.Add
    For i = 1 To oRS.Fields.Count - 1
        Cells(1, i).Value = oRS.Fields(i - 1).Name
    Next i
    oRS.MoveFirst
    i = 2
    Do While Not oRS.EOF
        For c = 1 To oRS.Fields.Count - 1
            Cells(i, c) = oRS.Fields(c - 1)
        Next
        i = i + 1
        oRS.MoveNext
    Loop
End Sub

© www.soinside.com 2019 - 2024. All rights reserved.