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

Excel Can Read to You
Customize Quick Access Toolbar. From All Commands, add Speak Cells or Speak Cells on Enter to QAT. Select cells. Press Speak Cells.
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,213,521
Messages
6,114,109
Members
448,548
Latest member
harryls

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