如何使用vba查询内联excel表?

时间:2012-09-20 08:36:47

标签: vba excel-vba excel-2010 excel

我显然缺乏关于excel查询的一些知识。我需要打印出一些自定义标签和每个工作人员的订购文章。

在我的例子中,我有2个表:

      [tabWorkers]
      ID        Name
      1         John
      2         Patrick


      [tabOrders]
      ID        Article   Amount
      1         Shoe      2
      1         T-Shirt   5
      2         T-Shirt   3

我正在循环使用tabWorker,对于每个工作,我想查询我的tabOrders表:SELECT * FROM tabOrders WHERE ID = 1

我想要的语法示例:

    Dim row As Range 
    For Each row In [tabWorkers].Rows 
      myID = row.Columns(row.ListObject.ListColumns("ID").Index).Value

      Write( row.Columns(row.ListObject.ListColumns("Name").Index).Value & " has ordered...<p>" )

      For Each (Article, Amount) In "SELECT * FROM tabOrders WHERE ID ='" & myID & "'")
        Write( Amount & " x " & Article & "<br>" )
      Next

    Next 

1 个答案:

答案 0 :(得分:0)

我之前在大型数据集上使用过this解决方案,只要选项卡上的数据定义明确,它就可以正常工作

基本上设置对ADO的引用然后定义与工作表的连接,记住每个工作表名称末尾的$:)

Dim cn as ADODB.Connection
Dim rs as ADODB.Recordset
Dim strSQL as String

Set cn = New ADODB.Connection
cn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & ActiveWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name

cn.Open

strSQL = "Select Distinct [Name] From [tabWorkers$] Order by [Name]"

Set rs = New ADODB.Recordset
rs.Open cn, strSQL, adOpenStatic, adLockReadOnly

'// then use the recordset
for each .......

rs.Close