Similar to user2140261's solution, use a worksheet_change event to trigger the change:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$A$1" Then
With ActiveSheet.Range("Table_Name").ListObject.QueryTable
.CommandText = ChangeParameter(.CommandText, "ParameterFlag", Range(Target.Address))
End With
ActiveWorkbook.RefreshAll
End If
End Sub
In the above, $A$1 is the location of the dynamic information (e.g., a date), the SQL table is Table_Name, and the ParameterFlag is the parameter within the SQL code to replace (see below).
This is the ChangeParameter function used to change the SQL code:
Function ChangeParameter(src As String, parameter As String, newValue As String)
'Replace src text surrounded by startParameter and endParameter with newValue
Dim startPosn As Long, endPosn As Long
Dim startParameter As String, endParameter As String
startParameter = "/*<" & parameter & ">*/"
endParameter = "/*</" & parameter & ">*/"
startPosn = 0
Do
startPosn = InStr(startPosn + 1, src, startParameter)
If startPosn Then
endPosn = InStr(startPosn + Len(startParameter), src, endParameter)
If endPosn Then
src = Left(src, startPosn + Len(startParameter) - 1) & newValue & Mid(src, endPosn)
Else
Exit Do
End If
End If
Loop While startPosn
ChangeParameter = src
End Function
If the desired SQL code were, for example:
SELECT * FROM mytable WHERE startDate > '7/1/2015'
Then this would be edited in the Command Text box to say:
SELECT * FROM mytable WHERE /*<StartDate>*/'7/1/2015'/*</StartDate>*/
And the calling line would be:
.CommandText = ChangeParameter(.CommandText, "StartDate", "'" & Range(Target.Address) & "'")
(the date is stored in the code as a constant, hence the necessity of surrounding the spreadsheet's value with single quotes). All of this works because comments surrounded by /* */
are ignored even if they are in the middle of a line, generally a poor coding practice but useful here.
All places in the original SQL code surrounded by the parameter flags (/*<StartDate>*/
and /*</StartDate>*/
in this case) would be replaced with the new value ("'" & Range(Target.Address) & "'" in this case). The next time the target cell $A$1 is changed, the call will be run again and the parameter changed again without any need to know what its previous value was.
Multiple calls to ChangeParameter could be used for each parameter to be changed, and for each SQL-based table containing parameters to be changed.
Of course, none of this would be necessary if parameter substitution worked for complex code...