VBA – Reverse a String of Text


Reverse a String of Text with VBA

The VBA Routine below allows the user to enter a string, and is then presented with the same string backwards. For example “Monday” becomes “yadnoM”:

Option Explicit

Private Sub CommandButton1_Click()

'Define Variables

Dim Original_String As String
Dim Reversed_String As String
Dim Next_Char As String

Dim Length As Integer
Dim Pos As Integer

'Get the Original String

Original_String = InputBox("Pls enter the original string: ")

'Find the revised length of the string

Length = Len(Original_String)

'Set up the reversed string
Reversed_String = ""

'Progress through the string on a character by character basis
'Starting at the last character and going towards the first character

For Pos = Length To 1 Step -1

    Next_Char = Mid(Original_String, Pos, 1)
    Reversed_String = Reversed_String & Next_Char
Next Pos

MsgBox "The reversed string is " & Reversed_String

End Sub

The main features of the code are :-

• It needs a command button to activate the code – on the click event
• The following variables are set up :-

o Original_String – the original string that will be reversed (“Monday”)
o Reversed_String – the reversed string (“yadnoM”)
o Next_Char – the next character in the string that will be reversed
o Length – the length of the string
o Pos – the current position in the string

• An InputBox to capture the string. This is stored in the variable “Original String”
• The Length of the String is calculated using the LEN function and stored in the variable Length
• A FOR…NEXT loop is set up to go through the string starting at the last character and working backwards one character at a time
• The next character in the original string (working backwards) is then added to the reversed string
• This loop is iterated until we have traversed the entire length of the string
• The reversed string is displayed in a MsgBox.

Download the Excel file here

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

alt text

Learn More!


<<Return to VBA Examples

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)