PDA

View Full Version : How to Set Current Selection as Range in Word



dfoster
08-18-2016, 06:34 AM
I could really use some help. I posted a similar question here not too long ago and am once again tearing my hair out trying to get my macros figured out.

I am trying to select a paragraph and compile a list of abbreviations to be inserted at the end of the selected paragraph. For some reason, I'm getting a list of all abbreviations through to the end of the document.

Here is what I have so far:

Dim oCol As New Collection
Dim oRng As Word.Range
Dim oDoc As Word.Document
Dim lngIndex As Long
Set oRng = Selection.Range
With oRng.Find
.Text = "<[A-Z]{1,8}>"
.MatchWildcards = True
While .Execute
On Error Resume Next
oCol.Add oRng.Text, oRng.Text
On Error GoTo 0
oRng.Collapse wdCollapseEnd
Wend
End With
For lngIndex = 1 To oCol.Count
Selection.InsertAfter oCol(lngIndex) & "," & " " & "; "
Next lngIndex
End Sub

Help would be much appreciated.

gmaxey
08-18-2016, 09:32 AM
You have discovered the "Runaway" range of VBA find and replace:


Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey
Dim oCol As New Collection
Dim oRng As Word.Range, oScope As Range
Dim oDoc As Word.Document
Dim lngIndex As Long
Set oRng = Selection.Range
Set oScope = oRng.Duplicate
With oRng.Find
.Text = "<[A-Z]{1,8}>"
.MatchWildcards = True
Do While .Execute
If oRng.InRange(oScope) Then
On Error Resume Next
oCol.Add oRng.Text, oRng.Text
On Error GoTo 0
oRng.Collapse wdCollapseEnd
Else
Exit Do
End If
Loop
End With
For lngIndex = 1 To oCol.Count
Selection.InsertAfter oCol(lngIndex) & "," & " " & "; "
Next lngIndex
lbl_Exit:
Exit Sub

End Sub

dfoster
08-18-2016, 10:00 AM
Greg, you. are. brilliant! I was just reading up on this on your website, so I think I'm beginning to understand...? Maybe? Thank you so much for your help. I was tearing my hair out.


You have discovered the "Runaway" range of VBA find and replace:


Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey
Dim oCol As New Collection
Dim oRng As Word.Range, oScope As Range
Dim oDoc As Word.Document
Dim lngIndex As Long
Set oRng = Selection.Range
Set oScope = oRng.Duplicate
With oRng.Find
.Text = "<[A-Z]{1,8}>"
.MatchWildcards = True
Do While .Execute
If oRng.InRange(oScope) Then
On Error Resume Next
oCol.Add oRng.Text, oRng.Text
On Error GoTo 0
oRng.Collapse wdCollapseEnd
Else
Exit Do
End If
Loop
End With
For lngIndex = 1 To oCol.Count
Selection.InsertAfter oCol(lngIndex) & "," & " " & "; "
Next lngIndex
lbl_Exit:
Exit Sub

End Sub