ChristianLinnell
ChristianLinnell

Reputation: 1398

Read undo history in VBA

I have a fairly simple bit of VBA in Word 2003 that changes the document's font to an 'eco font' (long story), and brings up the Print dialog.

When a user hits Cancel or OK, the code does an 'undo' to revert the change.

The problem is, sometimes when I press "OK" to print the document, two actions need to be undone ('font change', and 'update fields'). I can't seem to predict when this will happen.

Is there any way of reading the last item in Word's undo buffer? That way I can just keep pressing undo until the font change has been completed.

Edit: Final code (cut down):

ActiveDocument.Range.Bookmarks.Add ("_tempEcoUndoStart_") 
ActiveDocument.Content.Font.Name = "Nanonymus Eco Sans" 
Dialogs(wdDialogFilePrint).Show 
While ActiveDocument.Bookmarks.Exists("_tempEcoUndoStart_") 
    ActiveDocument.Undo 
Wend

Upvotes: 6

Views: 3657

Answers (3)

dotNET
dotNET

Reputation: 35400

For future readers, you can access undo actions list using the following VBA:

Application.CommandBars("Standard").controls("Undo").List

If you just need the count, use lListCount instead of List in the code above.

Upvotes: 1

Dirk Vollmar
Dirk Vollmar

Reputation: 176169

You can use a trick to have a 'transactional'-like undo in Word: At the beginning of the macro place a special bookmark on your entire document. You should remove this bookmark again when you are done with your macro. Now, when calling the Undo command, repeat the undo while there is your special bookmark in the document.

The following related question has the details:

Can I create an undo transaction in Word or Excel? (VSTO)

Upvotes: 5

Fionnuala
Fionnuala

Reputation: 91356

I have not tested, but perhaps you can use UndoClear before your actions, and a count on undo after?

ActiveDocument.UndoClear
ActiveDocument.Undo 2

Upvotes: 0

Related Questions