Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 142
  • Last Modified:

MS Query. Need to load .commandtext with variable but fails.

I have a macro where I run a MS Query several times but I want to run a different SQL Stored Procedure each time.
I am trying to load the .commandtext with data from a variable. This way I just need to change the variable and execute the same query instead of running 5 different queries.

I load  the variable with the correct  stored procedure to run in the .commandtext, but the query fails with syntax error.
ODBCCommand = "Array(" & Chr(34) & "exec MyStoredProc" & Chr(34) & ")"

This is the subroutine to run the MS Query.
Sub GetMyInfo()
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"ODBC;DSN=MyDBName;UID=username;Trusted_Connection=Yes;APP=Microsoft Office 2010;WSID=VirtualXP-PC" _
, Destination:=ActiveCell).QueryTable
'.CommandText = Array("exec MyStoredProc") <This will work but I have it commented out to use variable instead.
 .CommandText = ODBCCommand      <Even though variable is correct, query fails with "SQL Syntax error"
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.Refresh BackgroundQuery:=False  <<This is where it fails with "SQL Syntax error"
End With
End Sub
0
briandobo
Asked:
briandobo
1 Solution
 
Jeff DarlingDeveloper AnalystCommented:
You can build the array yourself like this:

Dim myExecSQL
Dim myODBCCommand
myExecSQL = "exec MyStoredProc"
myODBCCommand = Array(myExecSQL)

Open in new window

0
 
NorieCommented:
What happens if you just use this?
ODBCCommand = "exec MyStoredProc"

Open in new window

0
 
briandoboAuthor Commented:
WOW, sure thought I tried the:
ODBCCommand = "exec MyStoredProc"

But it worked for me.
Thanks
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now