我想设计一个接受任意数量布尔条件的Function或Sub,并将它们添加到IF语句中。我想象的代码是这样的:
Function comp (ParamArray list() As Variant)
If (list(0) = True) And (list(1) = true) ..... (list(last) = true) then
'random code
End If
End Function
其中list()将是表达式:
x = y-1,somethingToCompare <> anotherThing, etc...
如果我能添加&#34;和#34;那将会很有趣。作为另一个论点,改为&#34;或&#34;如果我愿意的话。
Function comp (VyVal compare as Boolean, ParamArray list() As Variant)
dim comparison as String???
If compare then
comparison = "and"
else
comparison = "or"
end if
If (list(0) = True) comparison (list(1) = true) ..... (list(last) = true) then
'random code
End If
End Function
最后的想法是使用这样的功能:
Sub code ()
if comp(True, condition1, condition2, ...) then
'random code'
End Sub
避免直接查看我写的代码,以免烫伤你的眼睛。
这样的东西是可行的还是我应该拿棒棒糖?
也许我以错误的方式看待这个问题,并且可以更轻松地做出类似甚至更好的事情。
答案 0 :(得分:1)
sub pointless(byval IsAnd as boolean, paramarray conditions())
dim i as long
for i=lbound(conditions) to ubound(conditions)
if IsAnd then
if not conditions(i) then exit sub
else
if conditions(i) then exit for
end if
next
'random code
end sub
但是您应该意识到该过程将接收传递给它的比较的结果,而不是比较本身。因此,首先要有这样的程序是没有意义的,你可以直接在你的代码中写:
if x = y-1 and somethingToCompare <> anotherThing then
'random code
end if
答案 1 :(得分:1)
Python(和其他一些语言)有一些有用的函数$this->getLayout()->createBlock('homepage/product_slider3');
和all()
,它们将一个数组(或其他一些可迭代的)布尔值作为输入,并返回True或False,具体取决于是否有些,所有或所有通过的布尔都是真的。您可以编写这些版本的VBA版本(使用any()
代替Some()
,因为Any()
恰好是VBA中有点模糊的关键字):
Any
您可以直接使用这些函数来有条件地调用代码。
可以说将上述定义更改为:
可能更有用Function All(ParamArray conditions()) As Boolean
Dim i As Long
For i = LBound(conditions) To UBound(conditions)
If Not conditions(i) Then
All = False
Exit Function
End If
Next i
All = True
End Function
Function Some(ParamArray conditions()) As Boolean
Dim i As Long
For i = LBound(conditions) To UBound(conditions)
If conditions(i) Then
Some = True
Exit Function
End If
Next i
Some = False
End Function
现在,如果您有一个条件的文字列表,则需要使用Function All(conditions As Variant) As Boolean
Dim i As Long
For i = LBound(conditions) To UBound(conditions)
If Not conditions(i) Then
All = False
Exit Function
End If
Next i
All = True
End Function
Function Some(conditions As Variant) As Boolean
Dim i As Long
For i = LBound(conditions) To UBound(conditions)
If conditions(i) Then
Some = True
Exit Function
End If
Next i
Some = False
End Function
而不是Some(Array(c1, c2, c3))
之类的调用,但是您可以灵活地传递整个条件。使用这个第二个定义,您可以编写如下内容(它回答您的原始问题):
Some(c1,c2,c3)
然后,例如,Sub Sometimes(when As String, ParamArray conditions())
Dim run As Boolean
Dim cond As Variant
cond = conditions
run = IIf(when = "All", All(cond), Some(cond))
If run Then
Debug.Print "Running random code"
Else
Debug.Print "Not running random code"
End If
End Sub
会导致Sometimes "Some",True,True,False
被打印。