我有一个带有2个表的MS SQL Server: FloatTable TagTable
使用Excel获取外部数据功能,我为每个表创建了查询,另外还有一个名为TagFloat的查询,它将FloatTable连接到TagTable各自的标签。
现在我想编写一个VBA代码,它将使用SQL命令(SELECT * ON ....)查询TagFloat,但我已经挂断了连接字符串。 VB抛出错误"初始化字符串的格式不符合OLE DB规范"。有人可以帮我解决这个问题吗?
这是主要的报告子:
Sub Report()
Dim SQLStrTGClockEnd As String
Dim SQLStrTGClockStart As String
SQLStrTGClockEnd = "SELECT Val FROM TagFloat WHERE TagTable.TagName = [SOUT]CTR_TG_RUNTIME_HOURS AND DateAndTime = SELECT MAX(DateAndTime) FROM TagFloat WHERE DateAndTime <= PeriodEnd)"
SQLStrTGClockStart = "SELECT Val FROM TagFloat WHERE TagTable.TagName = [SOUT]CTR_TG_RUNTIME_HOURS AND DateAndTime = SELECT MIN(DateAndTime) FROM TagFloat WHERE DateAndTime >= PeriodStart)"
Call BuildQuery1("TGClockEnd", SQLStrTGClockEnd)
End Sub
这是我的BuildQuery1 Sub:
Public Sub BuildQuery1(QueryName As String, SQLStr As String)
Dim oCn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim ConnString As String
Dim qt As QueryTable
ConnString = "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""TagFloat"";Extended Properties="""", Destination:=Range(""$A$1"")).QueryTable"
Set oCn = New ADODB.Connection
oCn.ConnectionString = ConnString
oCn.Open
Set oRS = New ADODB.Recordset
oRS.Source = SQLStr
oRS.ActiveConnection = oCn
oRS.Open
Set qt = Worksheets(1).QueryTables.Add(Connection:=oRS, _
Destination:=Range("B1"))
qt.Refresh
If oRS.State <> adStateClosed Then
oRS.Close
End If
If Not oRS Is Nothing Then Set oRS = Nothing
If Not oCn Is Nothing Then Set oCn = Nothing
End Sub