Home Technology Subscribe to RSS

How Do You Undo Macros In VB? Is It Actually Possible?

Answer Question

1 Answer - Sort by: Date | Rating

    Yes, this is possible by using different techniques for example; you can write your module in such a way that can help in undoing the macros.
    0 1

    Sky123 

    answered 2 years ago

    Add this code to any macro you want to be able to undo
    Sum Example()
    Call SaveUndo
    Application.OnUndo "Undo_Macro", "Undo_Macro" (put this at end of macro)
    End Sub

    Add this to the declarations at the top of the same module:
    Public workbooknumber As Integer
    Public currentworkbook As String
    Public newworkbook As String

    Then add the following two subs to complete the job:
    Sub SaveUndo()
    Dim Number As String

    If ActiveWorkbook.Path = "C:\TEMP" Then workbooknumber = workbooknumber + 1

    If workbooknumber = 0 Then Number = "" Else Number = workbooknumber

    currentworkbook = ActiveWorkbook.Name

    newworkbook = Replace(currentworkbook, ".xls", "")
    newworkbook = newworkbook + Number
    newworkbook = newworkbook + ".xls"

    SAVE:

    ActiveWorkbook.SaveCopyAs "C:\TEMP\" + newworkbook

    End Sub

    Sub Undo_Macro()

    Workbooks(currentworkbook).Close SaveChanges:=False

    Workbooks.Open ("C:\TEMP\" + newworkbook)

    MsgBox ("Make sure you save this file to the correct directory. " + newworkbook + " is currently saved in the temp directory")

    End Sub

    The above two macros temporarily save your file before running the desired macro. After running the original macro, select undo_macro on the undo button list and you will be reverted back to the saved version of the file.

    Hope this helps!
    Report
    Jonathanes

    Jonathanes

    commented 1 year ago

      More

      More

         
         

        Ask a Question via Twitter

        Send a question to @askblurtit and we will publish it online and send you a reply everytime you receive an answer.

        Blurtit Store

        Get T-shirts, hoodies, caps and more at the Blurtit store

        Blurtit International