如果四个变量相等

时间:2015-12-17 10:09:58

标签: vba excel-vba excel

我想检查四个不同的变量是否彼此相等。我得到了以下声明:

If a = b = c = d then

所有变量都包含" 06-12-2014",不幸的是,excel没有输入“如果' -statement”。 现在我发现这可能是一种写法,即if语句不正确。我当然可以做类似下面的事情,但我觉得必须有另一种方式,是吗?

If a=b and b=c and c=d then

3 个答案:

答案 0 :(得分:8)

您可以通过以下方式创建具有可变数量参数的灵活函数:

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

您可以将它与任意数量的变量一起使用

If AllSame(a, b, c, d, e, f) Then ....

答案 1 :(得分:2)

您可以尝试插入所有变量以进行比较,然后使用函数。 这是一个例子:

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

修改: 您还可以使用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

答案 2 :(得分:0)

我知道这已经得到了解答,但我想提供一个不需要循环的不同解决方案。

a = "06-12-2014"
b = "06-12-2014"
c = "06-12-2014"
d = "06-12-2014"
TestArr = Array(a, b, c, d)
If UBound(Filter(TestArr, a)) = 3 Then
    MsgBox "All match"
Else
    MsgBox "Doesnt match"
End If