I have been struggling with a need I had for several month and today I found the solution, or workaround if you'd like, to it.
The solution was inspired on a post I found here:
how to pass parameters to query in SQL (Excel)
And, even though I wanted to thank @mono código for the idea, I couldn't comment on the post anything on the original thread due to my lack of reputation. So I thought of posting this to thank and also to help others with the struggle.
My first approach for this was using Power Query, but doing modifications to the script afterwards is very complicated. This approach is much more simpler IMO.
It is basically getting the command text of your connection and modifying it on the fly:
With ActiveWorkbook.Connections("MyConnection").OLEDBConnection
queryOriginalText = .CommandText
queryPreText = .CommandText
queryPostText = Replace(queryPreText, "SET @From=@From", "SET @From='" & Range("StartDate") & "'")
queryPreText = queryPostText
queryPostText = Replace(queryPreText, "SET @To=@To", "SET @To='" & Range("EndDate") & "'")
queryPreText = queryPostText
queryPostText = Replace(queryPreText, "SET @OrderNo=@OrderNo", "SET @OrderNo='" & Range("OrderNo") & "'")
.CommandText = queryPostText
ActiveWorkbook.Connections("MyConnection").Refresh
.CommandText = queryOriginalText
End With
My script has 3 variables that I use as conditions to filter my data:
@From
, @To
and @OrderNo
. And, when I set those on my script I do it like this:
SET @From=@From
SET @To=@To
SET @OrderNo=@OrderNo
In my VBA I look for those specific strings and replace them one by one with values that the user input on the Sheet, on specific cell with Range names.
At the end I put back the original text so the strings to replace are always there when the user hit the button that runs the macro. This only works if you unchecked the option
otherwise you will get a runtime error.
I hope this helps