How to use UCase function in VBA?

In VBA (Visual Basic for Applications), the `UCase` function converts a specified string to uppercase. The syntax for the `UCase` function is quite simple:

UCase(String)

Where `String` is the string expression you want to convert to uppercase.

Here’s a step-by-step example showing how to use the `UCase` function:

Sub ConvertToUppercase()
    Dim originalText As String
    Dim uppercaseText As String

    originalText = "Hello, World!" ' Input string
    uppercaseText = UCase(originalText) ' Convert to upper case

    MsgBox uppercaseText ' Display the result in a message box
End Sub
  • Open Excel and press `ALT` + `F11` to open the Visual Basic for Applications editor.
  • Choose “Insert” > “Module” to insert a new module.
  • Type in a simple subroutine to test the `UCase` function:
  • To run the code, press `F5` while the cursor is inside the subroutine or go to “Run” > “Run Sub/UserForm”. A message box will pop up displaying “HELLO, WORLD!”.

The `UCase` function is useful when you want to perform case-insensitive string comparisons or ensure that text is formatted consistently in uppercase. Remember that `UCase` will not modify any non-letter characters, so numbers, punctuation, and spaces will be unaffected.

Note that VBA also has the opposite function called `LCase` which converts text to lowercase.

Here’s an example using both `UCase` and `LCase`:

Sub ConvertCase()
    Dim originalText As String
    Dim uppercaseText As String
    Dim lowercaseText As String

    originalText = "Hello, World!"

    ' Convert to upper case
    uppercaseText = UCase(originalText)
    MsgBox "Uppercase: " & uppercaseText

    ' Convert to lower case
    lowercaseText = LCase(originalText)
    MsgBox "Lowercase: " & lowercaseText
End Sub

When you run this `ConvertCase` subroutine, it will show two message boxes: one with the uppercase version of the string and one with the lowercase version.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project