views:

753

answers:

2

I asked this question previously but I don't think I was clear enough.

I need to write a Word VBA macro which will prompt the user to select some text by highlighting it after the macro has started running and then to process the new selection. This process will repeat an unknown number of times within the macro.

The only problem I have is figuring out how to get the VBA macro to 'pause' and allow the user to make this selection. If anyone is familiar with AutoCAD VBA, I am looking for the equivalent of the AcadSelectionSet.SelectOnScreen method. This seems so obvious and fundamental, but I just can't find anything in the Microsoft help files or searching online that shows me how to do this. Please help if you can!

+1  A: 

Should you perhaps be looking at the WindowSelectionChange event of the Application object?

In the special ThisDocument module, you need code like this:

Public WithEvents app As Application

Private Sub app_WindowSelectionChange(ByVal Sel As Selection)

MsgBox "The selection has changed"

End Sub

Obviously replace the MsgBox with useful code and use the Sel parameter to access the selection. If you want to try other events then use the dropdowns at the top of the ThisDocument module

To set it up, you need a macro like this in a normal code module:

Sub setUpApp()

Set ThisDocument.app = ThisDocument.Application

End Sub

After setUpApp has run once, the app_WindowSelectionChange event will be triggered whenever the selection changes

barrowc
A: 

You could use a modeless form to let your macro keep running until a certain condition was met:

Form designer:

  • Add a form.
  • Add one button.
  • Add one label.

Form code:

Option Explicit

Dim m_stopHere As Boolean
Dim m_timesDone As Long

Private Sub CommandButton1_Click()

    m_timesDone = m_timesDone + 1
    m_stopHere = Not DoStuff(m_timesDone)

    Me.Caption = "DoStuff was called " & m_timesDone & " time(s)."

       If m_stopHere Then
 MsgBox "Processing finished, closing form..."
 Unload Me
   End If
End Sub

Private Function DoStuff(times As Long) As Boolean

    Dim myCondition As Boolean

    If times < 5 Then
 MsgBox "You selected: " & Selection.Text
 Selection.Collapse wdCollapseEnd
 myCondition = True
    Else
 Me.Label1.Caption = "No more selections, thanks!"
    End If

    DoStuff = myCondition
End Function

Private Sub UserForm_Initialize()
    Me.Label1.Caption = "Please select some text in Word and press the button."
End Sub

Another code module:

Sub StopAndGo()
    UserForm1.Show vbModeless
End Sub
guillermooo