Ads 468x60px

Saturday, June 30, 2012

Make VBA String Comparisons Case In-sensitive [Quick Tip]

Make VBA String Comparisons Case In-sensitive [Quick Tip]:
Today, while answering a reader’s email, I wrote this VBA code,
If Target.Value = "yes" Then

'do something

End If

But I realized that my code would run only the Target cell has “yes” in it. It wont run if the target cell has “YES”, or “Yes” or “YeS”.
This is because by default, all VBA comparisons are binary. That means, “yes” ≠ “Yes”.
One quick work-around for this problem is to use UCASE to convert target.value to Uppercase and then compare, like this,
If UCASE(Target.Value) = "YES" Then

'do something

End If

But this seemed painful, especially, if I had to do similar comparison at multiple places in my code, I had to use UCASE() everywhere.
If only there is an option to tell VBA how to compare?!?
Well, there is an option.

Use Option Compare Text

If you write Option Compare Text at the top of your module, all the VBA comparisons with in that module will use Text comparison instead of Binary comparison. Thus, “yes” will be equal to “YES”.

Do you use Option Compare?

There are 3 settings for Option Compare.
  1. Option Compare Binary: This is the default setting. Compares everything at binary level.
  2. Option Compare Text: Used for situations like this.
  3. Option Compare Database: Can be used only with MS Access VBA. Uses Database Table settings to determine how to compare.
This is the first time I have used Option Compare Text. But it seems like an elegant way to tell Excel VBA how to compare. I will be using it more often.
What about you? Do you use Option Compare? What are your favorite tips & tricks? Please share with us using comments.

More on Excel VBA

VBA (or Macros) is how you can tell Excel to automate parts of your work. It is a powerful programming language built right in to Excel (and other MS Office applications) to help you do more. If you are new to VBA, why don’t you go thru our Free crash course?
  1. Introduction to VBA & Excel Macros
  2. Understanding Variables, Conditions & Loops in VBA
  3. Using Cells, Ranges & Other Objects in your Macros
  4. Putting it all together – Your First VBA Application using Excel
  5. My Top 10 Tips for Mastering VBA & Excel Macros
Also, go thru our VBA (Macros) article collection for more tips, tutorials & ideas.

0 comments:

Post a Comment