Introduction | Example | Tutorial | Applications
Introduction - VBA StrReverse
The VBA StrReverse function reverses the order of a string in Excel. In other words, StrReverse writes your string backward so the string
Example - VBA StrReverse
Sub ReverseStringSub()
str1 = "abcdef"
str1 = StrReverse(str1)
Debug.Print str1
End Sub
Make powerful macros with our free VBA Developer Kit It’s easy to copy and paste a macro like this, but it’s harder make one on your own. To help you make macros like this, we built a free VBA Developer Kit and wrote the Big Book of Excel VBA Macros full of hundreds of pre-built macros to help you master file I/O, arrays, strings and more - grab your free copy below.
Tutorial - VBA StrReverse
The macro above illustrates how the VBA StrReverse function takes a string and writes it in the reverse order. It changes the string
abcdef
to
fedcba
Believe it or not, it’s actually a useful feature. I used the StrReverse function to replace last occurrence of substring in a string in my article about the VBA Replace function.
Excel Function to Reverse a String
Excel doesn’t natively have an easy way reverse a string, but it’s easy to make your own function! Just copy and paste the following UDF into your Visual Basic editor:
Function ReverseString(v1 As Variant)
ReverseString = StrReverse(Trim(v1))
End Function
Now, anytime you want to reverse a string in Excel, you have a function to do it. If you want to reverse the order of the string in cell A1, just type =ReverseString(
into any cell in Excel, like this:
The Excel string is inverted!
The beauty of passing this function a variant is that it can reverse a lot more than just strings! It can reverse dates and numbers, too.
Application Ideas - VBA StrReverse
Reversing a string is great if you’re combining it with other string manipulation functions. I already showed you how I combined StrReverse with the VBA Replace function to replace last occurrence of substring in a string.
You don’t have to limit yourself to using this function in Excel, though. You can use it in Microsoft Word, too! If for some reason you want to flip the order of an entire document, you can certainly do that.
Comments
That’s all for this tutorial. When you’re ready to take your VBA to the next level, subscribe using the form below and follow me on Twitter.