gpt4 book ai didi

VBA ParamArray "conditions"在 IF 语句中使用

转载 作者:行者123 更新时间:2023-12-03 03:42:34 25 4
gpt4 key购买 nike

我想设计一个接受任意数量的 bool 条件并将它们添加到 IF 语句中的 Function 或 Sub。我想象的代码是这样的:

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...

如果我可以添加“and”作为另一个参数,如果我愿意的话,可以将其更改为“or”,那将会很有趣。

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

避免直接看我写的代码,以免灼伤你的眼睛。

这样的事情可能吗?还是我应该买 Lollipop ?

也许我以错误的方式看待这个问题,并且有一种更简单的方法可以做类似甚至更好的事情。

最佳答案

Python(和其他一些语言)具有有用的函数 all()any(),它们将 bool 数组(或其他一些可迭代的)作为输入并返回True 或 False 取决于传递的 bool 值是否部分、全部或全部不为 True。您可以编写这些的 VBA 版本(使用 Some() 而不是 Any(),因为 Any 恰好是 VBA 中有点晦涩的关键字) :

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 会导致打印 Running random code

关于VBA ParamArray "conditions"在 IF 语句中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41362612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com