Zach B
Zach B

Reputation: 534

Comparing Variable in VBA

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:

I have a VBA macro that assigns two variables in the first part of my code:

I have tried using the following statement, but it still does not work correctly:

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:

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

Answers (2)

Zach B
Zach B

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

isJustMe
isJustMe

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

Related Questions