How to compare strings in VBA

sony170

Board Regular
Joined
Jul 1, 2005
Messages
63
Usually i use the if string1 = string 2 then .... method.

but it only performs case-sensitve comparisons. so i looked online and found this code:

Code:
 compareResult = String.Compare(string1, string2, False, CultureInfo.InvariantCulture)

however, when i paste it in my code, i get the error saying

Expected "("

and it points to the period in between String and Compare.

what am i doing incorrectly?
 

Excel Facts

Do you hate GETPIVOTDATA?
Prevent GETPIVOTDATA. Select inside a PivotTable. In the Analyze tab of the ribbon, open the dropown next to Options and turn it off
you want to use strcomp() rather that string.compare()... I think the syntax is correct from there...
 
Upvote 0
Hatman,
A quick fix for your issue with non-case sentitive values would be

If UCase(Var1)=UCase(Var2) then


You convert the test values both to Upper case and do the compare. That way you don't affect the values, but the case doesn't matter.

HTH
Cal
 
Upvote 0
Cbrine: that's true, but strcomp also has an argument that allows you to specify whether the comparison is case sensitive or not:

vbUseCompareOption -1 Performs a comparison using the setting of the Option Compare statement.
vbBinaryCompare 0 Performs a binary comparison.
vbTextCompare 1 Performs a textual comparison.
vbDatabaseCompare 2 Microsoft Access only. Performs a comparison based on information in your database.


the value of 1 gives a test comparison without case sensitivity...
 
Upvote 0
hatman,
StrComp will definitly do the job, I was just providing you with another alternative option.
 
Upvote 0
This is all true, and here's another way:

Code:
Option Compare Text

Sub foo()
MsgBox "test" = "Test"
End Sub
 
Upvote 0

Forum statistics

Threads
1,213,563
Messages
6,114,332
Members
448,566
Latest member
Nickdozaj

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top