When you use bracket notation e.g. [A1]
you are using the EVALUATE
method:
Using square brackets (for example, "[A1:C5]") is identical to calling the Evaluate method with a string argument.
You can use this to do what you want by setting the Formula
property on a Range specified by bracket notation e.g.:
Option Explicit
Sub CompareCells1()
[L2:L10].Formula = "=IF(A2=N2,""yes"",""no"")"
End Sub
Note use of :
to get a Range
- using ,
s means you would do:
Option Explicit
Sub CompareCells2()
' you need to type each cell reference upto L10....
[L2, L3, L4, L5].Formula = "=IF(A2=N2,""yes"",""no"")"
End Sub
Which isn't as good as CompareCells1
.
You can assign the range to a Variant
but you can't simply compare two arrays like that - this won't work:
Option Explicit
Sub CompareCells3()
Dim var1, var2
var1 = [A2:A10]
var2 = [N2:N10]
' throws a Type Mismatch error
If var1 = var2 Then
' this will never happen
End If
End Sub
You can compare var1
and var2
per the faulty example above by using the Transpose
and Join
method suggested by Siddarth in his comment, per Tim Williams post but I think CompareCells1
method is the easiest for you if you need, or want, to use bracket notation.
Using ,
s to do comparison will result in a false positive. For example:
Option Explicit
Sub CompareCells4()
Dim var1, var2
var1 = [A2,A10]
var2 = [N2,N10]
' creates a string from the range values
If var1 = var2 Then
' this is a false positive - check the value of var1 and var2
[L2:L10] = "False positive"
End If
End Sub
Here var1
is just the value of A2
and var2
is just the value of N2
meaning even though you can set the range L2:L10
with bracket notation doesn't get you the correct comparison per your requirement.