VBA: Subroutine to Reverse a String

September 13th, 2008 | Categories: Strings | Tags: , , ,
-->

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

Can't get the tutorial to work for you? Need help with your code?
Get answers right away at our AE Excel Support Forums!
  1. Harry
    September 16th, 2008 at 14:19
    Reply | Quote | #1

    you could also use the strReverse() function, right?