Reputation: 534
I am looking for a method of comparing two string variables in VBA. The current statement I am using (which is not producing the desired result) is:
If Variable1 = Variable2 Then...
I have a VBA macro that assigns two variables in the first part of my code:
Dim Variable1 as String Variable1 = Left(Range("$F$3").Value, 4)
Dim Variable2 as String Variable2 = ("SheetName.B15")
I have tried using the following statement, but it still does not work correctly:
If Variable1 Like Variable2 Then...
Previously, the statement was working with a string comparison to the first variable, but it required that I hard-coded the "ABC" string. It looked like the below statement:
If Variable1 = "ABC" Then...
Does anybody know the syntax of a statement to compare two string variables, or could recommend a method for comparing them in a sub and return a binary result, which I could then compare?
Thanks!
Running VBA for Excel 2013 on Windows 8
Upvotes: 0
Views: 10627
Reputation: 534
Here is the solution:
I wasn't correctly assigning Variable2 and therefore, the function wasn't producing the desired result. Thanks everyone for their contributions, through the reply's - here's what we've come up with:
To compare two string variables in an existing sub, use:
If Variable1 = Variable 2 Then...
To compare two string variable in it's own sub, use:
Sub compare()
MsgBox StrComp("Stack", "stack") 'alerts -1
End Sub
Sub compare()
MsgBox StrComp("Stack", "stack", 1) 'Compare as text while ignoring case
End Sub
Upvotes: 0
Reputation: 5470
You can use StrComp
Sub compare()
MsgBox StrComp("Stack", "stack") 'alerts -1
End Sub
Sub compare()
MsgBox StrComp("Stack", "stack", 1) 'Compare as text while ignoring case
End Sub
The first one is case sensitive where the 2nd is not, of course you can replace the hardcoded values with variables
Upvotes: 3