Building Undo Into an Excel VBA Macro - vba

Excel macros do not seem to allow the use of "undo" after running them. Is there any way to bake undo functionality into a VBA macro in Excel?

Excel VBA has the Application.OnUndo function to handle this:
Public Sub DoSomething
... do stuff here
Application.OnUndo "Undo something", "UnDoSomething"
End Sub
Public Sub UnDoSomething
... reverse the action here
End Sub

My thought is pretty simple, as the first line in your macro save a copy in a backup directory then close that workbook and reopen the original. If you don't like the results of your macro run, pull up the saved workbook. Keep it simple eh?

I always save immediately before running my macros (during testing at least) then, if everything goes pear-shaped, I can just exit without saving and re-open it.
Baking it into the actual macro, you'll have to basically record the old state of everything that changes (cell contents, formulae, formatting and so on) in a list then have an undo macro which plays back that list in reverse order.
For example if your macro changes a cell C22 contents from "3" to "7" and formatting from "general" to "number, 2 decimals), your list would be:
C22 value 3
C22 format general
Playing this back in reverse order (with another macro) would revert the changes.
You could have a whole extra sheet to hold the macro undo information such as:
Step Cell Type Value
---- ---- ----- -------
1 C22 value 3
C22 format general
2...
It wouldn't integrate very well with the 'real' undo unfortunately, but I don't think there's any way around that.

Related

VBA - Possibility of saying that SheetChange in specific Range is "something like True"?

First, I must admit that I am completely newbie here and in VBA mostly too. Thank you for this forum! :)
I have program that reacts on SheetChange to save the data. However, if there is formula added by macro, it doesn't cause the SheetChange. Copying and inserting as values isn't possible - there are 7k rows and the program acts on every SheetChange (colors and other stuff) - the time is not bearable.
Is there any possibility to have EnableEvents = False (to turn of getting SheetChange), then specify the Range of the changed cells (always rather the whole column - there are 2 columns only that interest me) and then let the program save data. The coloring of the cells and so on would remain (this coloring and so on has to stay in the program)
Is it even possible that it would work? If it could, how should I tell the macro that specific Range has SheetChange?
Apologies if the question is totally stupid.
Thank you very much for reading at least.
In the sheet change event, just specify that it should only save when Target is within the specified range. For the formulas, use the Calculate event and repeat essentially the same code.
So, if you only want it to save when the changed cell is in the first column and only within a certain row range (for example), add If Target.Column = 1 And Target.Row > 5 And Target.Row <= 10 Then to your change event.
For the Formula issue, add the following routine
Private Sub Worksheet_Calculate()
'your code here
End Sub

How do I hotkey current sheet's VBA code?

I've had the issue of Worksheet_SelectionChange(ByVal Target As Range) triggering every time I click on something, which I don't want, as it means I have to wait every time I click in the actual sheet. I changed the code to Worksheet_Open, but that means I have to click the Run button whenever I want the code to run.
So I'm looking for a way of only running the current sheet's VBA code when I want to while I'm looking at the sheet (not while I'm in the VBA Editor). Ideally I'd be able to assign it to a hotkey using Application.OnKey, but I can't figure out how to refer to the sheet's code itself. The only solution I've found refers to an external macro, which isn't helpful, since I'm only wanting to use the code that's already in the sheet, as I'm using different macros for each sheet in the workbook.
Create a macro in a module for which you set the hot key, this macro will call the one you need:
CallByName ActiveSheet, ActiveSheet.Name & "Macro", VbMethod.
So you need to name the macros in the format of SheetNameMacro in each sheet.
More explanation: Trying to call a Sub with a String - VBA
Update
If your sheet names contains spaces then use this:
CallByName ActiveSheet, Replace(ActiveSheet.Name," ","_") & "Macro", VbMethod
and of course also replace spaces in your sheet (e.g. if your sheet called "list to delete" than macro name should be list_to_deleteMacro.

Is it possible to have a cell that has a formula and accepts entry at same time in excel?

Example:
A B
1 =vlookup(XX)
2
3
in cell A1 there is a Vlookup formula, Is it possible to enable user entry in this cell and override the formula then later restore the formula automatically when sheet is open again?
Even through VBA
Short, boring answer: nope.
A cell only ever has a keyed-in value, or a calculated formula. Can't have both.
Longer answer: maybe.
Shift everything 1 row down, and use row 1 to store your "original" formula - then hide that row (and pray the user isn't going to mess with it).
When the sheet is opened again sounds like you're confusing "workbook" and "worksheet" - you need to handle Workbook_Open if you want to run code when a workbook opens. Workbooks contain worksheets - it's the workbook that opens, not the sheets (sheets activate, but I doubt you would want to put that logic in there).
So, in the handler for Workbook_Open, write code that takes the formula in the hidden row and overwrites whatever is under it.
Another solution can be to hard-code the formula in the VBA code.
One possibility would be to store your Workbook as a template. Normally when a user opens the workbook by double-clicking, it will open whole new workbook based on the template, and they can modify it to their heart's content, save it, mail it to Grandma, etc.
The next person who comes along will double-click the template file and get the formula again, just as you designed it.
Short answer: Kind of, sort of
Long answer:
Save your workbook as a template. Every time someone will use it you'll see the orignal with formula, then if someone write over the formula, when using save your original will be kept intact.
What You need to do is:
press Alt + F11
select ThisWorkbook and paste this code:
Private Sub Workbook_Open()
Worksheets("Sheet1").Range("A11").Value = "asdf"
End Sub
Every time the workbook is opened, this script will run.
Instead of "Sheet1" you can write the name of the sheet you want to apply the script.
Inside the Range, You can define the cells you want to modify, You can use even multiple cells. Check this for more information about this.
After Value You can write what You want to be written inside the cell. You can write "=vlookup(XX)" and it will work.

Sheet.Activate changes sheet but continues to edit data on previous sheet

I have a dialog box with a couple of buttons that launch macros to activate and change to different sheets.
The problem I am having is after I click the button, the macro activates the new sheet and I see it. But when I go to delete data, add data or try to delete a row "Nothing happens" the data on the screen is still there. If I go back to the previous sheet, the cells and rows that I had intended to delete were deleted in that sheet. It is very wierd and never seen anything like that. It appears that my macro code is note doing enough to actually change to the new sheet. I do not have this problem if I click a different sheet tab to change to it. Or if I click the dialog button to go to the new sheet and quickly do a ctrl-pgDown and Ctrl-PgUp to change from another tab and back that seems to fix the problem.
This is the code in my macro I am using to try to change to the desired tab.
Private Sub Report1Button_Click()
On Error GoTo Handler
Sheets("Report1").Activate
If StayOpenBox.Value = False Then
Unload MainMenu
End If
Exit Sub
Handler:
MsgBox "Sheet 'Report1' not found or renamed"
End Sub
Thanks for any help or suggestions
UPDATE:
Here is code that I use to call the dialog box. I have a shape on the other sheet that is assigned to this macro to open dialog box
Sub ShowMainMenu()
With UserForm1
.Show
End With
End Sub
Also there is no further code to make edits to the new sheet. My Button click simply switches to the other sheet and when I attempt to make edits manually, they are actually done on the previous sheet which is not the one I am currently looking at. So anything I do, Bold text, delete text, delete row, etc, is not done on the current sheet I am looking at, but when I return to the previous sheet the changes where made there. Im on Excel 2013, I have reproduced this problem in 2 separate files, but I will try on a different computer and older version of excel. Screenshot of my situation is below.
UPDATE 2:
I ran this xlsm file on a 2nd computer with Xls 2007 and was not having the problem. So I ran the macro on a 3rd computer that also has Excel 2013 and it is experiencing the same problem. So it is not computer specific and seems to be a problem in XLS 2013 but not in XLS 2007. I will try to find a computer with Excel 2010 to test as well, but something about this code is causing a problem in 2013 but not in older versions of excel.
When you run VBA code, it will default to using the ActiveSheet if you don't define the Sheet. When you have objects/methods that you want performed on a specific sheet, you should always specify! You can do that one of two ways:
Sheets("Report1").[Object].[Method]
'or
Sheets("Report1").[Method]
or you can pass the Sheet name to a variable and use that for shorter code
Dim Report1 As Worksheet
Set Report1 = Sheets("Report1")
Report1.[Object].[Method]
'or
Report1.[Method]
Try changing the sequence of lines in your code. I had a similar situation and it turned out that I inserted the "delete sheet" code in between the commands that were copying data from sheet1 to sheet2. When I put the deletion lines (commands) after I finished copying sheets everything started to work correctly. Many commands activate one sheet while performing and this immediately disactivates another sheet. So if you used "ActiveSheet" sommand somewhere it may be incorrectly understood - the command may be executed not on the sheet you meant.
Just use the full address for the range you are trying to manipulate, for example instead of:
Sheets("mySheet").Activate
Range("A1:B10").Cut
Sheets("myOtherSheet").Activate
Range("A1:B10").Paste
use:
Sheets("mySheet").Range("A1:A10").Cut Destination:=Sheets("myOtherSheet").Range("A1:B10")
I just had the same problem, also with Excel 2013. So even if the thread is over 9 month inactive, I want to share my solution in case somebody gets here through a Google search.
The solution was really simple. Call the userform with:
UserForm1.show vbModeless

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

I am trying to write a simple macro to display a pop-up (vbOKOnly) if the value in a cell exceeds a certain value.
I basically have a worksheet with products and discounts. I have a formula in one cell, say A1, that shows the discount as a percent (50% or .5) effective discount of all the entries.
What I'm looking for is code to display a message box if the value of cell A1 exceeds say 50%, because the input of another cell pushed the discount over 50%.
Thanks!
You could add the following VBA code to your sheet:
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("A1") > 0.5 Then
MsgBox "Discount too high"
End If
End Sub
Every time a cell is changed on the sheet, it will check the value of cell A1.
Notes:
if A1 also depends on data located in other spreadsheets, the macro will not be called if you change that data.
the macro will be called will be called every time something changes on your sheet. If it has lots of formula (as in 1000s) it could be slow.
Widor uses a different approach (Worksheet_Calculate instead of Worksheet_Change):
Pros: his method will work if A1's value is linked to cells located in other sheets.
Cons: if you have many links on your sheet that reference other sheets, his method will run a bit slower.
Conclusion: use Worksheet_Change if A1 only depends on data located on the same sheet, use Worksheet_Calculate if not.
Essentially you want to add code to the Calculate event of the relevant Worksheet.
In the Project window of the VBA editor, double-click the sheet you want to add code to and from the drop-downs at the top of the editor window, choose 'Worksheet' and 'Calculate' on the left and right respectively.
Alternatively, copy the code below into the editor of the sheet you want to use:
Private Sub Worksheet_Calculate()
If Sheets("MySheet").Range("A1").Value > 0.5 Then
MsgBox "Over 50%!", vbOKOnly
End If
End Sub
This way, every time the worksheet recalculates it will check to see if the value is > 0.5 or 50%.
I don't think a message box is the best way to go with this as you would need the VB code running in a loop to check the cell contents, or unless you plan to run the macro manually. In this case I think it would be better to add conditional formatting to the cell to change the background to red (for example) if the value exceeds the upper limit.