在 SELECT Sql 语句中使用 VBA 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25665756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a VBA variable in SELECT Sql statement
提问by Paul Clint
Is their a way to use a declared VBA variable in a SELECT Sql statement as follows (I have a table called myTable
and i want to set the referenced field by passing the declared string myVar
) :
e.g passVar("English")
他们是一种在 SELECT Sql 语句中使用声明的 VBA 变量的方法,如下所示(我有一个名为的表myTable
,我想通过传递声明的字符串来设置引用的字段myVar
):例如 passVar("English")
NB: Am using Microsoft Access
注意:我正在使用 Microsoft Access
Private Function passVar(myVar as string)
Dim db As Database
Dim qdf As DAO.QueryDef
Dim stmnt As String
Set db = CurrentDb()
Set qdf = db.QueryDefs("SelectSubjectQuery")
stmnt = "SELECT [myTable].[myVar] = " &Chr$(34) & myVar & Chr$(34) & _
//other SQL statements go here
qdf.SQL = stmnt
End Function
Each time i run the query a dialog box appears asking for the value of mytable.myvar
instead of passing myvar
i.e Eglish as the referenced field on myTable
.
每次我运行查询时,都会出现一个对话框,询问 的值,mytable.myvar
而不是传递myvar
ie Eglish 作为 上的引用字段myTable
。
回答by rcfmonarch
Yes, build the SQL statement as a string like this:
是的,将 SQL 语句构建为这样的字符串:
stmnt = "SELECT " & [myTable] & "." & [myVar] & " = " &Chr$(34) & myVar & Chr$(34) & _
VBA should then fill in the names for MyTable and MyVar when the code is run and the string is built.
然后,在运行代码并构建字符串时,VBA 应填写 MyTable 和 MyVar 的名称。
回答by Paul Clint
stmnt = "SELECT [myTable]." & myVar & _
Got it to working by writing as above (no need for the equals sign as the string is passed through the function). Thanks for the insight @rcfmonarch
通过如上编写使其工作(字符串通过函数传递时不需要等号)。感谢@rcfmonarch 的见解