Using a selection as a variable with if/then statements and loops RRS feed

  • Question

  • I want to write a macro in Word 2003 that will make a selection, determine if the selection is a specific word, if so, move left a unit; if not delete the line, and then loop. I have made simple macros with the recorder, but this is a bit over my head.

    Here's what I have:

        Selection.MoveRight Unit:=wdWord, Count:=2, Extend:=wdExtend

        If Selection = "Count" Then
        Selection.MoveLeft Unit:=wdLine, Count:=1
        Selection.EndKey Unit:=wdLine, Extend:=wdExtend
        End If

    I think I need to have a variable, but how do I tell the variable to look at the selection? (I haven't gotten to the loop part yet.)

    Can someone help?

    • Moved by Reed KimbleMVP Wednesday, February 15, 2012 10:32 PM Word VBA Macro Help Request in VB General (From:Visual Basic General)
    Wednesday, February 15, 2012 9:28 PM


All replies

  • You can use:

        If Selection.Text = "Count" Then

    Selection.Text should show you the currently selected Text.  For details, see:

    Reed Copsey, Jr. -
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by Bruce Song Monday, March 5, 2012 3:10 AM
    Wednesday, February 15, 2012 9:36 PM
  • These forums are for Windows Forms applications and services, not VBA.

    I'll move this to a VBA related forum...

    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Wednesday, February 15, 2012 10:32 PM
  • Hi pj,

    Working with Selections is generally unnecessary and is much less efficient than working with Range objects. If you could explain a bit more about what you're trying to do, maybe some good advice could be given. FWIW, what you've posted so far suggests a Find/Replace process might be applicable.

    Paul Edstein
    [MS MVP - Word]

    • Marked as answer by Bruce Song Monday, March 5, 2012 3:10 AM
    Thursday, February 16, 2012 1:18 AM