VBA Button to Clear a Range of Cells - vba

As the title states, I am trying to create a button to clear a range of cells. Prior to clearing the cells, I have a dialog box pop up to confirm the selection. Here is my code:
Private Sub CommandButton1_Click()
If MsgBox("THIS WILL CLEAR EVERYTHING IN THE CART! Are you sure?", vbYesNo) = vbNo Then Exit Sub
Range("A28:AA47").ClearContents
End Sub
The code works when I'm in Design Mode and press "Play" but the button won't work on my sheet when I'm out of Design Mode.
Is the code completely ending itself when I select "No", to the point where it will not run again even if I hit the button again?

Your code looks a little incomplete. Try this instead:
EDIT: Cleaned it up a little more. No need for a vbNo, as if you don't select yes, the subroutine will simply end.
Private Sub CommandButton1_Click()
If MsgBox("THIS WILL CLEAR EVERYTHING IN THE CART! Are you sure?", vbYesNo) = vbYes Then
Range("A28:AA47").ClearContents
End If
End Sub

Related

How to implement a Cancel button on a userform?

I have a UserForm with a cancel button.
Sub DialogTest()
MyForm.Show
End Sub
Private Sub CancelButton_Click()
Unload Me
End
End Sub
I also tried MyForm.Hide, End by itself, cmdExit_Click.
The cancel button does not close the dialog nor does it cause the debugger to come up.
I was only able to replicate your issue when the Unload Me Sub was pasted in a Worksheet or Module. When the Sub is in the Userform, it works fine.
Here, the code is pasted in a module and does not close the Userform
Instead, from VBE, double click on your UserForm, then double click on your Cancel Button.
Then paste the code here

Using a VBA Dialog Box when closing a SpreadSheet

I would like a dialog box to appear when someone attempts to close an important Excel sheet. Namely I would like it to ask "Have you logged all Changes?" giving them the opportunity to click "Yes" or "No". If they click "Yes" the sheet will close, but if they Click "No" it will ask them to "Please log all changes in the Change Notes section".
Any and all help greatly appreciated.
This is the code you are looking for. It asks the question, and if No is clicked, it cancels the closing of the workbook:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ureply = MsgBox("Have you Saved All Changes?", vbYesNo)
If ureply = vbNo Then
Cancel = True
End If
End Sub
This code needs to go on 'ThisWorkbook' (Shown above the word 'Modules') on your VBA editor

Make my button say hello

I'm trying to get started with VBA for Excel and have added the "Developer" tab to the ribbon. I have also in Module1 added a small sub:
Sub Hello()
MsgBox ("Hello world!")
End Sub
Then I've created a button in spreadsheet 1, right click and assigned Hello as it's macro.
By now I'm thinking this should work, but when I click on it nothing happens.
Further more, if I open the VBA editor window again Module1 have been edited, not also containing my actions?
Sub Hello()
MsgBox ("Hello world!")
End Sub
ActiveSheet.Shapes.Range(Array("Button 2")).Select
Selection.OnAction = "Hello"
Range("G15").Select
ActiveSheet.Shapes.Range(Array("Button 2")).Select
Application.Goto Reference:="Hello"
Whats this mambo jambo? And why does the button not work? :(
And try the messagebox without the parantheses, only the quotes. So: msgbox "Blabla"
Delete the code after the sub routine: it was accidentally generated by the macro recorder (without a purpose).
Private Sub CommandButton1_Click()
Call hello
End Sub
Delete everything below End Sub ....this might have got recorded somewhere along the lines
Right click the button and go fo "View code" and adjust the automated code to look like the above. You'll need to be in "Design Mode" to get the menu when selecting the button:

Add "Are you sure?" to my excel button, how can I?

I have a button on my form that clears the entire 8 sheet workbook. I do want to clear it occasionally, but I would hate to do it by accident. I've tried googling it, but every result I've found assumes I have a much firmer grasp of VBA than I do. How can I make it so when the button is clicked a Dialog box pops up saying "This will erase everything! Are you sure? [Continue] [Cancel]"?
Thanks.
On your existing button code, simply insert this line before the procedure:
If MsgBox("This will erase everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub
This will force it to quit if the user presses no.
Create a new sub with the following code and assign it to your button. Change the "DeleteProcess" to the name of your code to do the deletion. This will pop up a box with OK or Cancel and will call your delete sub if you hit ok and not if you hit cancel.
Sub AreYouSure()
Dim Sure As Integer
Sure = MsgBox("Are you sure?", vbOKCancel)
If Sure = 1 Then Call DeleteProcess
End Sub
Jesse
Just make a custom userform that is shown when the "delete" button is pressed, then link the continue button to the actual code that does the deleting. Make the cancel button hide the userform.

How to stop VBA code running?

Say I have a button embedded into my spreadsheet that launches some VBA function.
Private Sub CommandButton1_Click()
SomeVBASub
End Sub
Private Sub SomeVBASub
DoStuff
DoAnotherStuff
AndFinallyDothis
End Sub
I'd like to have an opportunity to have some sort of a "cancel" button that would stop SomeVBASub execution at an arbitrary moment, and I'm not into involving Ctrl+Break here, 'cause I'd like to do it silently.
I guess this should be quite common issue, any ideas?
Thanks.
Add another button called "CancelButton" that sets a flag, and then check for that flag.
If you have long loops in the "stuff" then check for it there too and exit if it's set. Use DoEvents inside long loops to ensure that the UI works.
Bool Cancel
Private Sub CancelButton_OnClick()
Cancel=True
End Sub
...
Private Sub SomeVBASub
Cancel=False
DoStuff
If Cancel Then Exit Sub
DoAnotherStuff
If Cancel Then Exit Sub
AndFinallyDothis
End Sub
How about Application.EnableCancelKey - Use the Esc button
On Error GoTo handleCancel
Application.EnableCancelKey = xlErrorHandler
MsgBox "This may take a long time: press ESC to cancel"
For x = 1 To 1000000 ' Do something 1,000,000 times (long!)
' do something here
Next x
handleCancel:
If Err = 18 Then
MsgBox "You cancelled"
End If
Snippet from http://msdn.microsoft.com/en-us/library/aa214566(office.11).aspx
Or, if you want to avoid the use of a global variable you could use the rarely used .Tag property of the userform:
Private Sub CommandButton1_Click()
Me.CommandButton1.Enabled = False 'Disabling button so user cannot push it
'multiple times
Me.CommandButton1.caption = "Wait..." 'Jamie's suggestion
Me.Tag = "Cancel"
End Sub
Private Sub SomeVBASub
If LCase(UserForm1.Tag) = "cancel" Then
GoTo StopProcess
Else
'DoStuff
End If
Exit Sub
StopProcess:
'Here you can do some steps to be able to cancel process adequately
'i.e. setting collections to "Nothing" deleting some files...
End Sub
what jamietre said, but
Private Sub SomeVBASub
Cancel=False
DoStuff
If not Cancel Then DoAnotherStuff
If not Cancel Then AndFinallyDothis
End Sub
I do this a lot. A lot. :-)
I have got used to using "DoEvents" more often, but still tend to set things running without really double checking a sure stop method.
Then, today, having done it again, I thought, "Well just wait for the end in 3 hours", and started paddling around in the ribbon. Earlier, I had noticed in the "View" section of the Ribbon a "Macros" pull down, and thought I have a look to see if I could see my interminable Macro running....
I now realise you can also get this up using Alt-F8.
Then I thought, well what if I "Step into" a different Macro, would that rescue me? It did :-)
It also works if you step into your running Macro (but you still lose where you're upto), unless you are a very lazy programmer like me and declare lots of "Global" variables, in which case the Global data is retained :-)
K
~ For those using custom input box
Private Sub CommandButton1_Click()
DoCmd.Close acForm, Me.Name
End
End Sub
This is an old post, but given the title of this question, the END option should be described in more detail. This can be used to stop ALL PROCEDURES (not just the subroutine running). It can also be used within a function to stop other Subroutines (which I find useful for some add-ins I work with).
As Microsoft states:
Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement, and to clear variables*. I noticed that the END method is not described in much detail. This can be used to stop ALL PROCEDURES (not just the subroutine running).
Here is an illustrative example:
Sub RunSomeMacros()
Call FirstPart
Call SecondPart
'the below code will not be executed if user clicks yes during SecondPart.
Call ThirdPart
MsgBox "All of the macros have been run."
End Sub
Private Sub FirstPart()
MsgBox "This is the first macro"
End Sub
Private Sub SecondPart()
Dim answer As Long
answer = MsgBox("Do you want to stop the macros?", vbYesNo)
If answer = vbYes Then
'Stops All macros!
End
End If
MsgBox "You clicked ""NO"" so the macros are still rolling..."
End Sub
Private Sub ThirdPart()
MsgBox "Final Macro was run."
End Sub