查询工作表时如何修复VBA中的“自动化错误”

时间:2019-07-11 13:44:26

标签: sql excel vba

我正试图联接三个表,以按位置显示与“关键字”关联的类似项目的清单。

为此,我将我的产品列表DS加入SM,这是我的主列表,并在KEY上关联了相关产品,KEY是不同产品信息的索引。最后,我需要按位置提取这些项目的每个库存信息。

它在尝试建立记录集时从VBA抛出“自动化错误”。当我的SQL字符串中没有第二个联接(附加INV表)时,此方法有效。

Private Sub CommandButton1_Click()
Dim strFile
Dim strCon
Dim strSQL
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim I
Dim SQL

strSQL = "SELECT s1.KEY, s1.Item, Loc, QOH, Total_Ship_To_WIP, Tot_Opn+pick_Units, Reserve " _
& "FROM ([SM$] AS s1 " _
& "RIGHT JOIN [DS$] AS s2 ON s1.[KEY] = s2.[KEY]) " _
& "LEFT JOIN [INV$] AS s3 ON s2.[Item] = s3.[Full_Style]"

strFile = ActiveWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open strCon

rs.Open strSQL, cn 'error

For I = 0 To rs.Fields.Count - 1
    ActiveWorkbook.Sheets("Sheet1").Range("a10").Offset(0, I).Value = rs.Fields(I).Name
Next

ActiveWorkbook.Sheets("Sheet1").Range("a11").CopyFromRecordset rs

End Sub

0 个答案:

没有答案