Excel 2013 の場合、接続ダイアログの [パラメーター] ボタンは、クエリ テキストに "?" などのパラメーターが含まれていても無効のままです。
次のようにパラメータをクエリ テキストに挿入します。
declare @sd datetime, @ed datetime
set @sd = '2022-01-01'
set @ed = '2022-01-31'
select *
from dbo.Table1
where date between @sd and @ed
VBA で次を追加します。
Public SQLParams As New Dictionary 'Requred Reference "Microsoft Scripting Runtime"
Sub Button1_Click()
SQLParams("sd") = "'2022-02-01'"
SQLParams("ed") = "'2022-02-28'"
UpdateQuery SQLParams
End Sub
'Update params in all Query
Sub UpdateQuery(ByRef SQLParams As Dictionary)
Dim cn As WorkbookConnection
Dim odbcCn As ODBCConnection, oledbCn As OLEDBConnection
For Each cn In ThisWorkbook.Connections
If cn.Type = xlConnectionTypeODBC Then
Set odbcCn = cn.ODBCConnection
odbcCn.CommandText = SetParamValues(odbcCn.CommandText, SQLParams)
odbcCn.Refresh
ElseIf cn.Type = xlConnectionTypeOLEDB Then
Set oledbCn = cn.OLEDBConnection
oledbCn.CommandText = SetParamValues(oledbCn.CommandText, SQLParams)
oledbCn.Refresh
End If
Next
End Sub
Function SetParamValues(SQL As String, ByRef Params As Dictionary) As String
Dim re As New RegExp, Matches 'Requred Reference "Microsoft VBScript Regular Expressions 5.5"
Dim paramName As Variant, paramValue As String
SetParamValues = SQL
re.IgnoreCase = True
re.MultiLine = True
For Each paramName In Params.Keys()
re.Pattern = "(set\s+\@" + paramName + "\s*=\s*)(\'[^\']*\')"
paramValue = Params(paramName)
SetParamValues = re.Replace(SetParamValues, "$1" + paramValue)
Next 'For Each paramName In Params.Keys()
End Function