是否有一种特定的方法将SQL指令放在VBA代码中?
我想将SQL查询放入VBA代码,但如果我这样做,查询不起作用。如果我将查询指令放在Range(“A1”)中并在代码中引用它,则相同的查询可以正常工作。有没有办法在VBA代码中构建一个查询,以便它正常工作?当我添加WHERE
子句时,尤其会出现问题。
Sub CreateQueryTableWithParameters()
Dim qryTable As QueryTable
Dim rngDestination As Range
Dim strConnection As String
Dim strSQL As String
With Sheets("Sheet1")
.Activate
.Range("A:BY").Clear
End With
' Define the connection string and destination range.
strConnection = "ODBC;DSN=RDBWC;UID=;PWD=;DBALIAS=RDBWC;"
Set rngDestination = Sheet1.Range("A1")
' Create a parameter query.
strSQL = "SELECT *"
strSQL = strSQL & "FROM pdb2i.DI_NOS_OST_MVT_01"
strSQL = strSQL & "WHERE COR_ID <> '90003'"
' Create the QueryTable.
Set qryTable = Sheet1.QueryTables.Add(strConnection, rngDestination)
' Populate the QueryTable.
qryTable.CommandText = strSQL
qryTable.CommandType = xlCmdSql
qryTable.Refresh False
With Columns("D:D")
.NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* ""-""??_);_(@_)"
.AutoFit
End With
With Columns("H:J")
.AutoFit
End With
Rows("1:1").Select
Selection.AutoFilter
Columns("H:H").ColumnWidth = 5
Columns("I:I").ColumnWidth = 5
Columns("J:J").ColumnWidth = 5
Columns("M:M").ColumnWidth = 5.14
Columns("N:N").ColumnWidth = 4
End Sub
我想补充一点,我已尝试使用[]括号,但仍无法正常工作
strSQL = "SELECT *"
strSQL = strSQL & "FROM pdb2i.DI_NOS_OST_MVT_01"
strSQL = strSQL & "WHERE [COR_ID] <> '90003'"
答案 0 :(得分:3)
您在语句之间缺少空格:
strSQL = "SELECT *"
strSQL = strSQL & "FROM pdb2i.DI_NOS_OST_MVT_01"
strSQL = strSQL & "WHERE [COR_ID] <> '90003'"
会屈服:
SELECT *FROM pdb2i.DI_NOS_OST_MVT_01WHERE [COR_ID] <> '90003'
哪个不是有效的SQL查询, 只需将其更改为:
strSQL = "SELECT * "
strSQL = strSQL & "FROM pdb2i.DI_NOS_OST_MVT_01 "
strSQL = strSQL & "WHERE [COR_ID] <> '90003' "