VBA convert Boolean/Bool to String

VBA - Visual Basic for Application

If you program with VBA to make certain tasks in the Microsoft Office world easier, you can’t avoid the fact that sometimes different data types have to be converted into a string, e.g. a date, integer numbers or double numbers. This article is about how to convert a boolean value, as the data type Boolean, which can accept True and False, into a string.

Simple solution with CStr()

To convert a Boolean variable into a string, simply use the CStr function. This powerfully overloaded function is also suitable for other data types to convert them into a string.

In this example, we simply set a bool value (myBool) to True, convert it to a string value, and assign it to the variable myString. This in turn we bring to display in a MessageBox.

Screenshot VBA code converting boolean to string with CStr() function
Convert Bool to String using CStr()-Function
Sub BooleanToString()
    Dim myBool As Boolean
    Dim myString As String
    myBool = True
    myString = CStr(myBool)
    MsgBox myString, vbOKOnly, "Show Bool as String"
End Sub

If you are using another language package in Microsoft Office then localization intervenes here. So it is not simply “True” or “False” output, because “True” or “False” are translated to the chosen language. In this case Excel immediately carries out the translation from “True” to your set up language.

Alternative individual conversion: If statement

Admittedly, with such a conversion one can often do nothing directly with the values “True” or “False“. If necessary, these are still suitable for filtering in Excel. But with a simple If-Then-Else statement you can also make an individual conversion and assign your own values to the string variable depending on the Boolean variable.

Screenshot VBA-Code with bool value and string output
Using If-Then-Else for converting Boolean to String
Sub BooleanToMyString()
    Dim myBool As Boolean
    Dim myString As String
    myBool = False
    If myBool = True Then
        myString = "Okay!"
        myString = "Not Okay!"
    End If
    MsgBox myString, vbOKOnly, "Show Bool as String"
End Sub

This should be the preferred variant in many cases. One simply checks whether a value is “True” and then outputs an individual text.

Bestseller No. 1
Bestseller No. 2
The Little VBA Book
  • Grieves, Robin (Author)

Leave a Reply

Your email address will not be published. Required fields are marked *