Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If four variables are equal

Tags:

excel

vba

I want to check if four different variables are equal to each other. I've got the following statement:

If a = b = c = d then

All of the variables contain "06-12-2014", unfortunately excel doesn't enter the 'if'-statement. Now I found out this may be a way of writint the if statement that isn't correct. I can of course make something like the following, but I feel like there must be another way, is there?

If a=b and b=c and c=d then
like image 734
Grafit Avatar asked Dec 17 '15 10:12

Grafit


2 Answers

You can create a flexible function with variable number of parameters in this way:

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

You can use it with any number of variables

If AllSame(a, b, c, d, e, f) Then ....
like image 124
A.S.H Avatar answered Sep 27 '22 17:09

A.S.H


You can try inserting all variable to compare into an array and then use a function. Here an example:

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

EDIT: You can also use ParamArray to pass directly the values and to avoid declaring a new array:

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
like image 27
genespos Avatar answered Sep 27 '22 15:09

genespos