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
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 ....
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With