我经常使用MS Excel的"获取外部数据"来创建简单的报表,通过对数据库运行查询并在Excel中漂亮地显示出来。Excel的强大功能,如筛选和数据透视表以及熟悉的用户界面,使其非常适合此类应用。但是,Microsoft Query的一个限制是您无法向不能以图形方式显示的查询中添加参数,这严重限制了您能编写的SQL。
"无法在不能以图形方式显示的查询中添加参数"错误是否有解决方案?
"无法在不能以图形方式显示的查询中添加参数"错误是否有解决方案?
Excel的SQL Server查询界面不允许自定义参数。解决方法是创建一个通用的Microsoft Query,然后添加参数,再将带参数的查询粘贴到连接属性中。以下是Excel 2010的详细步骤:
简易解决方案(无需 VBA)
从这里开始,通过在 SQL 中添加“?” 直接编辑参数。与以前的方式一样工作,但不会有烦人的提示。
?
,那么下次刷新数据时它将提示您输入连接的值!神奇。当您查看连接的属性时,参数按钮现在将处于活动状态,可以像平常一样使用。Sub UpdateQuery
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
' If you do have multiple connections you would want to modify
' the line below each time you run through the loop.
odbcCn.CommandText = "select blah from someTable where blah like ?"
ElseIf cn.Type = xlConnectionTypeOLEDB Then
Set oledbCn = cn.OLEDBConnection
oledbCn.CommandText = "select blah from someTable where blah like ?"
End If
Next
End Sub
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
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
是的 - 解决方案是将工作簿保存为XML文件(例如“XML电子表格2003”),并在记事本中将此文件作为文本进行编辑! 使用记事本的“搜索”功能查找查询文本,并将数据更改为“?”。
保存并在Excel中打开,尝试刷新数据,Excel将监视参数。