如何在SQL Query上修复运行时错误91?

时间:2016-08-17 15:41:33

标签: excel-vba vba excel

此代码从用户请求两个输入变量,然后在查询中使用这些变量从公司内部软件返回数据。我从公司的其他人使用的宏中修改了这段代码。

我的宏:

  • 无问题编译
  • 遇到运行时错误'91':未设置对象变量或With块变量
    • 发生在With.Selection.ListObject.QueryTable

注意:一些细节,例如公司名称,服务器,登录等已删除!

Option Explicit

Public EN As String
Public REV As String
Dim SearchString As String
Dim SearchString1 As String
Dim SearchString2 As String


Public Sub QueryImport()

EN = Import_Details.EN.Value
REV = Import_Details.REV.Value

Application.ScreenUpdating = False

Unload Import_Details

SearchString = EN
SearchString = EN & Chr(37)
SearchString = EN & Chr(47) & REV & Chr(37)

Sheets("Import").Range("A2").Select

With Selection.ListObject.QueryTable
     .Connection = _
    "ODBC;DRIVER=SQL Server;SERVER=XXXXXX-       XX;UID=XX;PWD=XXXXXX;APP=Microsoft Office 2013;WSID=XXXX;DATABASE=XXX-Live"
    .CommandText = _
    "SELECT Enquirys_list_with_Parts.""Item No"", Enquirys_list_with_Parts.Description, Enquirys_list_with_Parts.""Part No"", Enquirys_list_with_Parts.Qty, Enquirys_list_with_Parts.Price, Enquirys_list_with_Parts.Total" & Chr(13) & "" & Chr(10) & _
    "FROM ""Emax-Live"".dbo.ENQUIRY_LINES_LIST ENQUIRY_LINES_LIST, ""Emax-Live"".dbo.Enquirys_list_with_Parts Enquirys_list_with_Parts, ""Emax-Live"".dbo.Quote_Line_Qty_Drop_list Quote_Line_Qty_Drop_list" & Chr(13) & "" & Chr(10) & _
    "WHERE Enquirys_list_with_Parts.""Enquiry No"" = ENQUIRY_LINES_LIST.""Enquiry No"" AND Enquirys_list_with_Parts.""Part No"" = Quote_Line_Qty_Drop_list.Part_No AND ENQUIRY_LINES_LIST.Enquiry_Line_id = Enquirys_list_with_Parts.Enquiry_Line_id AND ((Enquirys_list_with_Parts.""Enquiry No"" Like '" & SearchString1 & "' And Enquirys_list_with_Parts.""Enquiry No"" Like '" & SearchString & "') AND (Quote_Line_Qty_Drop_list.""Quote No"" Like '" & SearchString2 & "'))" & Chr(13) & "" & Chr(10) & _
    "ORDER BY Enquirys_list_with_Parts.""Item No""" _

    .Refresh BackgroundQuery:=False
End With

Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:0)

您正在尝试引用从未设置过的对象。

Dim MyQueryTbl as QueryTable

Set MyQueryTbl = Sheet1.QueryTables(1)

然后你可以操纵你的MyQueryTbl对象。