VBScript: how to find the difference between two strings that look identical

Tag: string , vbscript , qtp Author: hanhanfeng Date: 2010-06-21

There are two strings "test_name" that are compared in a VB script. They have to be identical, and they look identical in debug viewer, but StrCompare(string1, string2) returns 1.

History. This is a test in QTP. The first string is read from Excel. The second one is from a windows application. QTP reads a value from Excel, enters it to a windows form, and then reads the same value from another place. The test passes if these two values are identical.

How to find a difference in these two strings so that I can correct the test?

Best Answer

I would suggest using a For loop, Mid, and Asc, to compare the actual characters one by one. Something like (untried code):

' Presume input strings named s1 and s2
' Assume Len(s1) = Len(s2)
Dim i

For i = 1 to Len(s1)
   If Asc(Mid(s1, i, 1)) <> Asc(Mid(s2, i, 1)) Then
        Msgbox "Strings differ at character " & i
    End If
Next 'i

If they are equal by this test, and unequal by StrComp then... I don't really know. Perhaps try the same thing with LenB and AscB to see if it's a Unicode or encoding issue somehow.


Thanks a lot. I used your code to find out that it was my mistake. I used a wrong variable to compare with.
Last line should be "Next" without "i".
No, the i can be there actually.
@katmoon @Trefex I 'learned' VBScript after VB 3... in one it's optional, in the other it's wrong, and I can never remember which is which
In VBScript it's an error if you include the variable. It's just "Next" by itself.

Other Answer1

Most likely you have trailing spaces at the end (or something else that prints like a space). Try to print them like this:

Debug.Print "*" & string1 & "*"
Debug.Print "*" & string2 & "*"

and see what you get.


Thanks. Definitely no extra spaces. I see values in double quotes in debug viewer: "test_name"
Are both string1 and string2 printed with double quotes?
+1 @danbystrom - A very common issue in automated testing is whitespace mismatches, and they do not show up well in log files, so you want to add your own custom logging to be able to tell the difference. For example, comboboxes/dropdowns will often be padded with spaces, so you need to trim the space prior to comparison.

Other Answer2

Did you try using the parameter vbTextCompare in your StrComnpare ? This would do case-insensitive comparison of both strings.

I also would have recommended what the 2 above said.

So it would be:

StrCompare(String1, String2, vbTextCompare)

Kind Regards,


Yes, I took that into account. Thanks.