【发布时间】:2023-12-23 16:06:01
【问题描述】:
在 VBA 中(在 MS Access 项目中),我想定义一个 if 语句,其中部分语句存储在变量中。
为了说明我的问题,这里是一个简单的例子:
Sub Test_String_Insertion_Into_IfStatement()
Dim strInsert As String
strInsert = "10 > 5" ' Or any other stuff that would return "TRUE"
If "" & "'"strInsert"'" & "" Then
Debug.Print "Hurray, it works!"
Else
Debug.Print "Sorry, my friend. Try something else..."
End If
End Sub
现在,问题是,这不起作用。我想,诀窍是找到与号、引号、撇号和/或 Chr(34) 的正确组合。
我做了很多实验,测试了我能想象到的所有变化,但到目前为止我还没有找到一个可行的组合。我测试的大部分内容都返回“类型不匹配”错误。
现实世界的应用程序...
上面的例子相当简单。在我的实际任务中,我想插入一个更长的字符串作为 if 语句的一部分。这是我在现实世界中的一个 if 语句,最终将被替换为使用变量插入语句的大部分的东西(这是:除了正确的“If”和“Then”之外的所有内容):
If oRs.Fields(strTitField) Like "*" & arrWCs(r).varTERM1 & "*" Then
它使用记录集的字段和用户定义的变量类型(数组)。
请注意,我想以可变方式插入的 if 语句部分本身有引号和和号! (现实世界的 if 语句已被证明是有效的。但现在我想使用变量将其插入到我的 if 语句中。)
目的是,使用变量插入,我可以非常快速地在多个 if 语句之间切换,具体取决于整个函数的需要。)
为方便起见,我添加了一个在 if 语句中使用 & 和引号的简单示例:
Sub Test_String_Insertion_Into_IfStatement_2()
Dim strIfClause As String
Dim strXYZ As String
strXYZ = "ouse"
strInsert = "'Mouse' Like '*' & strXYZ & '*'" ' Just a guess, doesn't work
If "" & """strInsert""" & "" Then
'The resulting if-statement should be:
'If "Mouse" Like "*" & strXYZ & "*" Then '(Taken as such, this works!)
Debug.Print "Good!"
Else
Debug.Print "Not good!"
End If
End Sub
【问题讨论】:
-
使用
Application.Evaluate()方法。例如,str = "10 > 5"传入Application.Evaluate(str)将返回一个Boolean True。