Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL syntax inside VBA Code

Tags:

sql

mysql

excel

vba

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'"
like image 765
Tommeck37 Avatar asked Sep 16 '26 12:09

Tommeck37


1 Answers

You are missing a space between statements:

strSQL = "SELECT *"
strSQL = strSQL & "FROM pdb2i.DI_NOS_OST_MVT_01"
strSQL = strSQL & "WHERE [COR_ID] <> '90003'"

Would yield:

SELECT *FROM pdb2i.DI_NOS_OST_MVT_01WHERE [COR_ID] <> '90003'

Which isn't a valid SQL query, Simply change it to:

strSQL = "SELECT * "
strSQL = strSQL & "FROM pdb2i.DI_NOS_OST_MVT_01 "
strSQL = strSQL & "WHERE [COR_ID] <> '90003' "
like image 107
Uri Goren Avatar answered Sep 18 '26 01:09

Uri Goren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!