1

I'm trying to compare two string values in VBA but I've found a weird quirk of VBA ( or it seems so ). See Below:

If I do the following:

Debug.Print("Same" & StrComp(Me.txtFirstName.Value, Me.txtFirstName.Value, vbTextCompare))
Debug.Print("Different" & StrComp(Me.txtFirstName.Value, Me.txtFirstName.OldValue, vbTextCompare))

I get:

Same: 0
Different: 1

Which is something I would expect. However. If I then try to do the following:

Debug.Print("Same" & StrComp(Me.txtFirstName.Value, Me.txtFirstName.Value, vbTextCompare) = 0)
Debug.Print("Different" & StrComp(Me.txtFirstName.Value, Me.txtFirstName.OldValue, vbTextCompare) = 0)

I then get:

Same: False
Different: False

For reference, the values should be (for example)

Same test: "Jane", "Jane"
Different test: "Jane", "John"

Which is not what I expect. I know I'm doing something incorrectly but I'm not exactly sure what.

Any help is appreciated.

EDIT:

When I now enter this into an if statement:

If (StrComp(Me.txtFirstName.Value, Me.txtFirstName.OldValue, vbTextCompare) = 0) Then
    Debug.Print ("Hello")
Else
    Debug.Print ("Goodbye")
End If

I get a result of Goodbye

JamieRhys
  • 206
  • 6
  • 24
  • 1
    The code you have shown could not result in this output, it results in Error 13: Type mismatch because it's parsed as `("Same" & StrComp(s1, s2, vbTextCompare)) = 0`. Having fixed it to `"Same" & (StrComp(s1, s2, vbTextCompare) = 0)` you will get `SameTrue` rather than `Same: False`. – GSerg Mar 23 '22 at 07:33

1 Answers1

2

Your issue is that it first concatentates "Different" & StrComp(Me.txtFirstName.Value, Me.txtFirstName.OldValue and then compares that with =0.

And Different1 is not 0 therefore you get False.

use parenthesis to evaluate the comparison before concatenating:

Debug.Print("Same" & (StrComp(Me.txtFirstName.Value, Me.txtFirstName.Value, vbTextCompare) = 0))
Debug.Print("Different" & (StrComp(Me.txtFirstName.Value, Me.txtFirstName.OldValue, vbTextCompare) = 0))

Actually this code

Debug.Print("Same" & StrComp(Me.txtFirstName.Value, Me.txtFirstName.Value, vbTextCompare) = 0)

should have end up in a Type Mismatch error.


If StrComp(Me.txtFirstName.Value, Me.txtFirstName.Value, vbTextCompare) = 0 Then
    MsgBox "They are the same"
Else
    MsgBox "They are different"
End If
Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73