PDA

View Full Version : [SOLVED:] microsoft word reverse text string or words order



jo55
05-25-2015, 04:21 PM
hi
im working with microsoft word (i have 2003 and 2013) want to reverse order of text and/or string of words
in other words i need two diferent macros

1. to reverse words/letters like "vba express com" to "abv sserpxe moc"

2. to reverse paragraph/selected words like "vba express com" to "com express vba"

i found a macro for microsoft excel and i need help re-writing it for word

this is what i have



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Sub ReverseText()
'Updateby20131128
Dim Rng As Range
Dim WorkRng As Range
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
For Each Rng In WorkRng
xValue = Rng.Value
xLen = VBA.Len(xValue)
xOut = ""
For i = 1 To xLen
getChar = VBA.Right(xValue, 1)
xValue = VBA.Left(xValue, xLen - i)
xOut = xOut & getChar
Next
Rng.Value = xOut
Next
End Sub



thank you for your help

gmaxey
05-25-2015, 05:04 PM
Try:


Sub ReverseWords()
Dim strIn As Variant, strOut As String, lngIndex As Long
'Get the selected text, split by blanks into words
strIn = Split(Selection)
'Construct the output string
For lngIndex = 0 To UBound(strIn)
strOut = strIn(lngIndex) & " " & strOut
Next
'Replace the selected text
Selection = Trim(strOut)
lbl_Exit:
Exit Sub
End Sub

Sub TransposeText()
Dim oRng As Word.Range
Dim lngCase As Long
Dim strText As String
Dim lngIndex As Long
Dim bSpace As Boolean
With Selection
If .Words.Count = 1 Then
Set oRng = .Range
lngCase = oRng.Words(1).Case
strText = StrReverse(oRng.Text)
oRng.Text = strText
oRng.Case = lngCase
Else
Set oRng = .Range
For lngIndex = 1 To oRng.Words.Count
If oRng.Words(lngIndex).Characters.Last = Chr(32) Then bSpace = True
lngCase = oRng.Words(lngIndex).Case
strText = StrReverse(Trim(oRng.Words(lngIndex).Text))
If bSpace Then strText = strText & " "
oRng.Words(lngIndex).Text = strText
bSpace = False
Next
End If
End With
lbl_Exit:
Exit Sub
End Sub

See:http://gregmaxey.mvps.org/word_tip_pages/installing_employing_macros.html forinstructions to employ the VBA code provided above.

jo55
05-25-2015, 05:24 PM
hi greg
thanks alot for your quick response

i tryed both scrips and the secend one works great

unfortunately in the first script i am getting a error by this word "UBound"

gmaxey
05-25-2015, 07:30 PM
Change Dim strIn as String to Dim strIn as Variant. See edited post above.

jo55
05-25-2015, 10:52 PM
thanks a million greg :hi: