应用程序定义或对象定义的QueryTable错误

我试图从SQL中的表中获取数据,并使用VBA将其导出到工作表。

我一直无法弄清楚如何做到这一点,而不是每次创build一个新的数据连接。

这是我现在正在做的事情:

我将SQL查询放入一个单元格,并给variables名称,如“#ID”和“date”。 在macros中,我将用实际的信息replace这些variables中的数据。 到目前为止,这并没有给我任何问题,因为使用SQL时查询运行没有问题。 要将数据从SQL导出到我的工作表中,我使用的代码可以在其他工作簿中使用; 但是,当我在这个工作簿中运行它,我得到错误“应用程序定义或对象定义的错误”。 这是完整的macros:

Sub CurrentBreakout() Dim SQLString As String Dim ID As String Dim Date As String Dim year As String Dim daycount As String SQLString = Range("CurrentBreakout") 'This is the range where the query is stored ID = Range("ID") Date = Range("CurrMonth") year = Range("CurrYear") daycount = Range("CurrDayCount") SQLString = Replace(SQLString, "#ID", ID) SQLString = Replace(SQLString, "#Date", Date) SQLString = Replace(SQLString, "#CurrDayCount", daycount) SQLString = Replace(SQLString, "#CurrYear", year) With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _ "ODBC;DSN=____________;UID=________;Trusted_Connection=Yes;APP=Microsoft Office 2010;WSID=________;DATABASE=_______;" _ , Destination:=Range("CurrCon")).QueryTable .CommandText = SQLString .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .BackgroundQuery = True .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .PreserveColumnInfo = True .ListObject.DisplayName = "Table_CurrCon" .Refresh BackgroundQuery:=False End With End Sub 

我得到“.Refresh BackgroundQuery:= False”的错误。 这可能不是完成这个任务的最好方法,但这是我知道的唯一方法。