Gra*_*fit 10 excel vba excel-vba
我想检查四个不同的变量是否相等.我有以下声明:
If a = b = c = d then
Run Code Online (Sandbox Code Playgroud)
所有变量都包含"06-12-2014",遗憾的是excel没有输入'if'语句.现在我发现这可能是一种写法if语句不正确的方法.我当然可以做类似下面的事情,但我觉得必须有另一种方式,是吗?
If a=b and b=c and c=d then
Run Code Online (Sandbox Code Playgroud)
您可以通过以下方式创建具有可变数量参数的灵活函数:
Function AllSame(ParamArray ar()) As Boolean
AllSame = True : If UBound(ar) < 1 Then Exit Function
For Each p In ar
If p <> ar(0) Then
AllSame = False : Exit Function
End If
Next
End Function
Run Code Online (Sandbox Code Playgroud)
您可以将它与任意数量的变量一起使用
If AllSame(a, b, c, d, e, f) Then ....
Run Code Online (Sandbox Code Playgroud)
您可以尝试将所有变量插入数组中进行比较,然后使用函数。这里有一个例子:
Sub MyTest()
Dim TestArr() As Variant
a = "06-12-2014"
b = "06-12-2014"
c = "06-12-2014"
d = "06-12-2014"
TestArr = Array(a, b, c, d)
If Equal_In_Array(TestArr) Then
MsgBox ("All are Equal")
Else
MsgBox ("Something isn't Equal")
End If
End Sub
Public Function Equal_In_Array(mArr() As Variant) As Boolean
Equal_In_Array = True
For x = LBound(mArr) To UBound(mArr)
If mArr(x) <> mArr(LBound(mArr)) Then
Equal_In_Array = False
Exit For
End If
Next x
End Function
Run Code Online (Sandbox Code Playgroud)
编辑:您还可以使用ParamArray
直接传递值并避免声明新数组:
Sub MyTest()
a = "06-12-2014"
b = "06-12-2014"
c = "06-12-2014"
d = "06-12-2014"
If Are_Equal(a, b, c, d) Then
MsgBox ("All are Equal")
Else
MsgBox ("Something isn't Equal")
End If
End Sub
Public Function Are_Equal(ParamArray mArr() As Variant) As Boolean
Equal_In_Array = True
For x = LBound(mArr) To UBound(mArr)
If mArr(x) <> mArr(LBound(mArr)) Then
Equal_In_Array = False
Exit For
End If
Next x
End Function
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
372 次 |
最近记录: |