PDA

View Full Version : Macro to move numbers to the end of a sentence



chuknzig
01-06-2023, 02:05 PM
If someone would kindly help, I would appreciate it greatly.
Is it possible to write a macro for this?
I end up with documents loaded with these types of sentences that I need to move the reference numbers to the end.

The sentence I have:

BB1.4.4 - Sample sentence text that goes on for a while and then ends here.

What I want to have:

Sample sentence text that goes on for a while and then ends here (BB1.4.4).

macropod
01-06-2023, 05:39 PM
There is no reliable way of doing this at the sentence level.

VBA, for example, has no idea what a grammatical sentence is. For example, consider the following:
Mr. Smith spent $1,234.56 at Dr. John's Grocery Store, to buy: 10.25kg of potatoes; 10kg of avocados; and 15.1kg of Mrs. Green's Mt. Pleasant macadamia nuts.
For you and me, that would count as one sentence; for VBA it counts as 5 sentences.

gmayor
01-06-2023, 11:00 PM
While Paul is correct with regard to sentences, and such a task might even be impossible with access to the complete document. However I find that in these forums some people write 'sentence' when they are referring to sentences that form a paragraph. If the text is a complete paragraph, the following macro will format that paragraph if the cursor is placed in it before running it:

Sub Macro1()
Dim oRng As Range, oEnd As Range
Set oRng = Selection.Paragraphs(1).Range
Set oEnd = oRng.Duplicate
oEnd.End = oEnd.End - 1
oEnd.MoveEndWhile ".", wdBackward
oEnd.Collapse 0
oRng.Collapse 1
oRng.MoveEndUntil "-"
oRng.End = oRng.End + 2
If Len(oRng.Text) < 11 Then
oEnd.Text = Replace(oRng.Text, " - ", "")
oEnd.InsertBefore " ("
oEnd.InsertAfter ")"
oRng.Text = ""
End If
Set oRng = Nothing
Set oEnd = Nothing
End Sub

chuknzig
01-09-2023, 08:52 AM
Thank you gmayor. It does work and I did mean one single sentence without additional punctuation per my example. :)
Your help is greatly appreciated.