我尝试从SQL中的表中获取数据,然后使用VBA将其导出到工作表。
我每次都无法在不创建新数据连接的情况下弄清楚如何做到这一点。
以下是我现在所做的事情:
我将SQL查询放入一个单元格中,并给出变量名称,如#'#ID'和"日期"。在宏中,我将用实际信息替换这些变量中的数据。到目前为止,这并没有给我任何问题,因为在使用SQL时查询运行没有问题。要将数据从SQL导出到我的工作表,我使用的代码适用于其他工作簿;但是,当我在此工作簿中运行它时,我收到错误"应用程序定义或对象定义错误"。这是完整的宏:
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"收到错误。这可能不是完成此任务的最佳方式,但这是我所知道的唯一方式。