Is there a specific way to put SQL instructions inside VBA code?
I would like to have SQL query put into VBA code but if I do so query does not work. The same query works fine if I put query instructions in Range("A1") and refer to it in a code. Is there a way to build a query inside VBA code so that it works fine? Problem especially arises when I add the WHERE clause.
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
I would like to add that I've tried with [] parentheses and it still does not work
strSQL = "SELECT *"
strSQL = strSQL & "FROM pdb2i.DI_NOS_OST_MVT_01"
strSQL = strSQL & "WHERE [COR_ID] <> '90003'"
strSQL = strSQL & " FROM pdb2i.DI_NOS_OST_MVT_01"andstrSQL = strSQL & " WHERE COR_ID <> '90003'"