Make VBA code undo in one step

Is there a way to make the VBA code of a Word 2013 macro run as a block, so if I reverse it, it won't reverse the macro in the individual steps it takes to execute? I would like macros to be more like built-in functions.

I have a macro that moves the cursor to the end of a word and then removes the previous three letters. If I undo it, I see each of the three letters appear one after the other.

Perhaps I did not name this right. I was wondering if there is any code to wrap the macro to make Word treat the macro as a built-in Work command that does everything once, rather than a series of recorded steps. Then if I run the macro and decide I don't like the results, I can click on undo and the entire macro is rewound and canceled.

+3


a source to share


1 answer


This should do what you want:

Method one:

Sub YourMacroName
    Dim objUndo As UndoRecord 
    'Declares the variable objUndo of the UndoRecord type
    Set objUndo = Application.UndoRecord 
    'sets the object to an actual item on the undo stack
    objUndo.StartCustomRecord ("Undo Stack Display Text")
    'Tells Word where to begin "recording" the undo record
    'This item also lets you set the text you want to appear in the undo drop-down in word.
        Selection.MoveRight Unit:=wdWord 
        'Moves to the end of the current word
        Selection.MoveLeft Unit:=wdCharacter, Count:=3, Extend:=True 
        'Selects the last three letters of the word
        Selection.Delete
        'Deletes the last three letters of the word
    objUndo.EndCustomRecord
    'Denotes the End of The Undo Record
End Sub

      

You can also look at Microsoft's article on Using Application.UndoRecord Property .

Alternatively, as @Matteo NNZ pointed out, you can just remove three characters at a time. To do this, use the code below.



Method two:

Sub YourMacroName
     Selection.MoveRight Unit:=wdWord 
    'Moves to the end of the current word
    Selection.MoveLeft Unit:=wdCharacter, Count:=3, Extend:=True 
    'Selects the last three letters of the word
    Selection.Delete
    'Deletes the last three letters of the word
End Sub

      

The disadvantage of the second method is that you cannot control the name of the item in the undo dropdown.

Both methods are limited in that they do not restore the cursor to its original position.

+4


a source







All Articles