[RESOLVED] macro help, multiple text selects
Hey all.
I've written a few macros to make my office work faster, but I'm stuck on this one.
I need to be able to select two separate pieces of text manually, using the CTRL key, and then run a macro that can handle these two pieces of text.
Ultimately I'm dropping them into a database.
The database part is all working.
Where I'm stuck is on dealing with the selection in the macro.
For example, if I select the word "hello" and then later down the document select "world" while holding down CTRL, the two items are both selected.
But if I write a quick macro: Msgbox(Selection.Text)
the output is "world"
I need a way to get at both selected pieces.
Anybody?
thanks.
Re: macro help, multiple text selects
Add the following function to your module:
vb Code:
Private Function GetSelectedRanges() As Range()
Dim doc As Document, rng As Range, tempStyle As Style
Dim selectedRanges() As Range, selectionCount As Long
Set doc = ActiveDocument
ReDim selectedRanges(100) As Range
'' Add a temporary style to the document
Set tempStyle = doc.Styles.Add("$$MyTemporaryStyle##", wdStyleTypeCharacter)
Selection.Style = tempStyle
'' Now find this style in the document and work with it.
Set rng = doc.Range
With rng.Find
.ClearFormatting
.Style = tempStyle
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
While rng.Find.Execute
selectionCount = selectionCount + 1
If selectionCount > UBound(selectedRanges) Then ReDim Preserve selectedRanges(selectionCount * 2) As Range
Set selectedRanges(selectionCount) = rng.Duplicate
Wend
End With
ReDim Preserve selectedRanges(selectionCount) As Range
'' Remove the temporary style we added.
tempStyle.Delete
GetSelectedRanges = selectedRanges
End Function
Sample Usage:
vb Code:
Sub Macro1()
Dim rng() As Range, i As Integer
rng = GetSelectedRanges
For i = 1 To UBound(rng)
Debug.Print rng(i)
Next
End Sub
Re: macro help, multiple text selects
Hey.
Thanks a lot.
that worked well for what I needed, was very easy to adapt.