Normalize a variable

Tags
Summary

Convert a variable that can have many formats, into one format.

Situation

You have a variable that can have many formats, maybe leading and trailing spaces, and upper- and lowercase. You want to test the variable with an If.

Needs

A variable that can have many formats.

Provides

A variable in a single format.

Action

Say you have a variable tPet, that can have extra spaces, and uncertain casing. You want to test tPet for a few different values. You could do this:

  • ' Is it a common pet?
  • If Trim(LCase(tPet)) = "cat" Or Trim(LCase(tPet)) = "dog" Or Trim(LCase(tPet)) = "bird" Then
  •     MsgBox "A common pet."
  • EndIf

Works, but messy. A better way is to create a new variable, and covert the many formats into one. Then it's easy to test the new variable. For example:

  • ' Convert tPet into one format: lowercase, no leading or trailing whitespace.
  • tNormalizedPet = Trim(LCase(tPet))
  • ' Is it a common pet?
  • If tNormalizedPet = "cat" Or tNormalizedPet = "dog" Or tNormalizedPet = "bird" Then
  •     MsgBox "A common pet."
  • EndIf