简体   繁体   English

VBA 将查询中的参数传递给 ADO 连接“1004”:应用程序定义或对象定义错误

[英]VBA Passing parameter in query to ADO connection '1004': Application-defined or object-defined error

It seems that in the command text, I am not able to use a parameter as a table name so I am now trying to hard code it into the VBA the query but I am running into the '1004': Application-defined or object-defined error.似乎在命令文本中,我无法将参数用作表名,因此我现在尝试将其硬编码到 VBA 查询中,但我遇到了“1004”:应用程序定义或对象-定义的错误。 Attached is a screenshot of the command text I am using but doesn't seem to work.附件是我正在使用但似乎不起作用的命令文本的屏幕截图。 The code below I added is causing the error: The Connection Properties pop up box我添加的下面的代码导致了错误:连接属性弹出框

With ActiveWorkbook.Connections("Query1").OLEDBConnection
        .BackgroundQuery = True
        .CommandType = adCmdText
        .CommandText = "SELECT * FROM [DBO].[Refresh_" & UserName & "] ORDER BY [Item No];"
End With

I would appreciate any help anyone can give me in regards to the query within the "Connections" properties box or the vba code.对于“连接”属性框或 vba 代码中的查询,任何人都可以给我任何帮助,我将不胜感激。 Either would work.两者都行。

Thanks in advance, Paul提前致谢, 保罗

Depending on how you set up the connection, it will either have an ODBCConnection , or an OLEDBConnection property (but not both).根据您设置连接的方式,它将具有ODBCConnectionOLEDBConnection属性(但不能同时具有两者)。

If you break down the code a little you can put a watch on the connection and see what properties are populated:如果稍微分解一下代码,您可以观察连接并查看填充了哪些属性:

Sub Tester()
    
    Dim conn As WorkbookConnection 'put a Watch on this and step through....
    
    Set conn = ThisWorkbook.Connections("TestQuery")
    
    With conn.ODBCConnection
            .BackgroundQuery = True
            .CommandType = xlCmdSql    '<<<<  not adCmdText
            .CommandText = "select * from ops$rs3.hts_scientist"
    End With

End Sub

Watch window:观看 window:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM