Thursday, April 2, 2015

HowTo: Convert a string to proper case in a label expression

Summary

Instructions provided describe how to use a label expression to convert a string that is upper case, lower case or mixed case to proper case. For example, if a string that is in the following formats:

"hello world"
"HELLO WORLD"
"hELLO wORLD"
"Hello World"

The following label expression will convert the string to: "Hello World".

For information on how to do the equivalent steps in the ArcMap field calculator, see the link in the Related Information section below.


Procedure

In the ArcMap field calculator, use the VBA expression StrConv to convert a string to proper case. However, the default label expression parser VBScript does not have this method. The following label expression works around this VB Script limitation:

  1. Open the Label Expression dialog box.
  2. Click the Advanced button.
  3. Use the following code when converting only one field. Remember to change the name of the field [MyFieldName] to match the field name in the two locations below where it is referenced. 
    Function FindLabel ([MyFieldName])
      FindLabel = PCase([MyFieldName])
    End Function

    Function PCase(strInput)
      Dim iPosition
      Dim iSpace
      Dim strOutput
      iPosition = 1
      Do While InStr(iPosition, strInput, " ", 1) <> 0
        iSpace = InStr(iPosition, strInput, " ", 1)
        strOutput = strOutput & UCase(Mid(strInput, iPosition, 1))
        strOutput = strOutput & LCase(Mid(strInput, iPosition + 1, iSpace - iPosition))
        iPosition = iSpace + 1
      Loop
      strOutput = strOutput & UCase(Mid(strInput, iPosition, 1))
      strOutput = strOutput & LCase(Mid(strInput, iPosition + 1))
      PCase = strOutput
    End Function
       4. Use the following code when converting many fields at once. Remember to change the field names in the code below. Add more fields if required.

      Function FindLabel ([MyFieldName1], [MyFieldName2], [MyFieldName3])
        FindLabel = PCase([MyFieldName1] & " " & [MyFieldName2] & " " & [MyFieldName3])
      End Function
      
      Function PCase(strInput)
        Dim iPosition
        Dim iSpace
        Dim strOutput
        iPosition = 1
        Do While InStr(iPosition, strInput, " ", 1) <> 0
          iSpace = InStr(iPosition, strInput, " ", 1)
          strOutput = strOutput & UCase(Mid(strInput, iPosition, 1))
          strOutput = strOutput & LCase(Mid(strInput, iPosition + 1, iSpace - iPosition))
          iPosition = iSpace + 1
        Loop
        strOutput = strOutput & UCase(Mid(strInput, iPosition, 1))
        strOutput = strOutput & LCase(Mid(strInput, iPosition + 1))
        PCase = strOutput
      End Function