Simple VBA for Undo - Run-time error '1004'

bvbull200

New Member
Joined
Jul 29, 2013
Messages
24
I have a pretty simple bit of code that I'm having trouble with. All it is supposed to do is Undo the last action, then format a target cell. If it is run twice in succession, I get the error - Run-time error '1004' undo of object _application failed. For instance, if I type the word "test" in a cell, then run the macro, it will remove the word from the cell (revert to the previous state). If I run it again without typing anything new on the sheet, I get the error.

Code:
Sub Undo()'
' Undo Macro
'
Application.Undo
        Range("C4").Interior.ColorIndex = Int((44 - 1 + 1) * Rnd + 1)
'
End Sub

It's okay if I can't actually Undo two consecutive actions, but is there something I can put in to avoid the error? Ideally, I would type the word "test" in a cell, then run the macro and it removes the word. Then run it a second time and nothing happens (or, better yet, the interior color change still happens).

I hope this makes sense. It is for a little proof of concept I need to have done.

Thank you all for your help.
 

Excel Facts

Copy formula down without changing references
If you have =SUM(F2:F49) in F50; type Alt+' in F51 to copy =SUM(F2:F49) to F51, leaving the formula in edit mode. Change SUM to COUNT.
Code:
Sub Undo() '
' Undo Macro
'
On Error Resume Next
Application.Undo
        Range("C4").Interior.ColorIndex = Int((44 - 1 + 1) * Rnd + 1)
'
End Sub
 
Upvote 0
Man, I'm a dummy. I forgot about that line. Still pretty green with regards to VBA.

Thanks for the quick response.
 
Upvote 0

Forum statistics

Threads
1,223,963
Messages
6,175,656
Members
452,664
Latest member
alpserbetli

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top