|
-
Feb 23rd, 2011, 07:48 AM
#1
Thread Starter
Frenzied Member
[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.
Wen Gang, Programmer
VB6, QB, HTML, ASP, VBScript, Visual C++, Java
-
Feb 23rd, 2011, 10:10 AM
#2
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
Last edited by Pradeep1210; Feb 23rd, 2011 at 10:22 AM.
-
Feb 23rd, 2011, 12:36 PM
#3
Thread Starter
Frenzied Member
Re: macro help, multiple text selects
Hey.
Thanks a lot.
that worked well for what I needed, was very easy to adapt.
Wen Gang, Programmer
VB6, QB, HTML, ASP, VBScript, Visual C++, Java
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|