访问Excel VBA SQL Join

时间:2015-06-27 07:46:18

标签: sql excel vba excel-vba

我在访问数据库中有两个表,我想从excel vba执行CRUD操作。虽然我能够单独对各个表执行CRUD,但它同时在两个表上执行CRUD时会说一些JOIN错误。这是 Tables& Relationship他们之间。 我试过这样的东西,但它说了一个JOIN错误

"Select CustomerT.First_Name,ProductT.Product_Name,CutomerT.Age From CustomerT Inner Join ProductT ON Customer.ID = ProductT.Customer_ID"

我的主要目的是通过输入客户ID来了解客户和他/她订购的产品的详细信息。 请建议做什么。

以下是我正在使用的完整代码

Sub CommandButton1_Click()
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Access2Excel\DB1.accdb;Persist Security Info=False;"
'Open Db connection
con.Open
Set rs.ActiveConnection = con
rs.Open "Select CustomerT.First_Name,ProductT.Product_Name,CutomerT.Age From CustomerT Inner Join ProductT ON CustomerT.ID = ProductT.Customer_ID "             
StartRow = 3
Do Until rs.EOF

'first field
Cells(StartRow, 4) = rs.Fields(0).Value
'second field
Cells(StartRow, 5) = rs.Fields(1).Value
'Third field
Cells(StartRow, 6) = rs.Fields(2).Value


rs.MoveNext
StartRow = StartRow + 1
Loop
Set rs = Nothing
con.Close
Set con = Nothing
End Sub

1 个答案:

答案 0 :(得分:0)

T中似乎缺少Customer.ID。联接应该是:

Select CustomerT.First_Name,ProductT.Product_Name,CustomerT.Age 
From CustomerT Inner Join ProductT ON CustomerT.ID = ProductT.Customer_ID

修改

还将CutomerT.Age更改为CustomerT.Age,感谢LondonRob!