2012-09-20 75 views
1

我顯然缺乏對excel查詢的一些知識..我需要打印出一些自定義標籤與每個工作人員的訂購文章。如何查詢內聯excel表與vba?

在我的例子,我有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 
+0

我能過濾器適用於我的表的末尾$: [ tabOrders] .ListObject.Range.AutoFilter字段:= 1,Criteria1:= myID 但當循環[tabOrders] .Rows,我仍然得到我所有的行.. –

+0

只回應您的評論,但看看'SpecialCells (xlCellTypeVisible)'範圍對象的方法。 – markblandford

回答

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