How to select certain options from an alert in VBA - vba

I have a macro that calls a number of other macros which work fine, but I would like to make it more automated - at the moment it requires users to click 'Yes' or 'No' or other similar options as the macro runs.
A sample is below:
Sheets("Macro").Select
Sheets("Hidden").Visible = True
Application.ScreenUpdating = False
Application.DisplayAlerts = False
intList = MsgBox("HerpDerp?", vbYesNo + vbQuestion)
If intList = vbNo Then Exit Sub
If (Range("asd").Value = "sdf" Or Range("asd").Value = "dfg") Then
othermacro1
othermacro2
Else
othermacro3
othermacro4
End If
Sheets("Macro").Select
Application.DisplayAlerts = True
Sheets("Hidden").Visible = False
MsgBox "DerpHerp", vbInformation + vbOKOnly, "Save"
End Sub
Through troubleshooting I would have thought that setting alerts to automatically not display this would circumvent the problem, but users need to click more divers buttons than 'yes' or 'no' in order to continue with the macro, which may be why this is occurring (though I would have anticipated that this would just make the alert not appear...).
Any help on this would be greatly appreciated and any additional info required can easily be supplied.
Thanks in advance for the help!

Check this sample code and hope this helps you:
Source Code:
Sub MsgBoxDemo()
Dim Answer As Long
Answer = MsgBox("Select Yes or No", vbExclamation + vbYesNo, "Reply")
If Answer = vbYes Then
MsgBox "Yes"
End If
If Answer = vbNo Then
MsgBox "No"
End If
End Sub

Related

AutoClose macro..ending closing action based on answer without save prompt

I have a word document with field in the end of the document to update filepath, last saved date & last save by. I need these to update on the closing of the file.
I am running an Autoclose macro that updates the fields. The problem is that I need the workbook to save BEFORE these fields are updated, so the last save date and the last save by will update.
I am going to recreate the "Would you like to save changes" message box at the start of the macro, with a yes/no/cancel option. I have 2 questions
1- If the user says No or Cancel..how do I suppress the system generated Would you like to save to avoid a repeat of the same question (or pass along their response to my version of the question to the system so they don't see it)
2 - If the pick cancel, how do I stop the system action of closing the file?
What i have below I found online , the sendkeys (ESC) is not stopping the system close.`
Sub AutoClose()
'if the document is already saved
If ActiveDocument.Saved = True Then
'update all fields, save, close without prompt
Else
'which would be the document's status is not saved
answer = MsgBox("Yes No Cancel Example", vbYesNoCancel)
'above is do you want to save
If answer = vbYes Then
MsgBox "Yes"
ElseIf answer = vbNo Then
'dont save, dont update, close file without prompt
Else
'this is the cancel, so dont update, dont close
ActiveDocument.Saved = True
SendKeys "{ESC}"
End If
End If
End Sub
Perhaps:
Sub AutoClose()
Application.ScreenUpdating = False
Dim Rslt
With ActiveDocument
If .Saved = True Then
Call UpdateFields
.Save
Else
Rslt = MsgBox("Save changes and close, or discard changes and close?", vbYesNoCancel)
If Rslt = vbYes Then
Call UpdateFields
.Save
ElseIf Rslt = vbNo Then
.Saved = True
Else
Call UpdateFields
Application.ScreenUpdating = True
Exit Sub
End If
End If
End Sub
Sub UpdateFields()
With ActiveDocument
.Fields.Update
.PrintPreview
.ClosePrintPreview
End With
End Sub

Displays msgbox Excel VBA

My quest to complete my project is nearly done im just facing one final issue with my code.
Sub DeletePatientCheck()
'check if patient record exists before deleting'
Dim s As Worksheet
On Error Resume Next
'Check if Patient Record already exists'
For Each s In Sheets
If s.Name = Selection Then
Worksheets(s.Name).Activate
Call DeleteRecord
End If
Next s
MsgBox "*No Patient Record Found!*"
End Sub
Sub DeleteRecord()
'Confirm delete?'
Answer = MsgBox("Are you sure you want to delete this Patient Record?",
vbQuestion + vbYesNo, "Delete Patient Record")
If Answer = vbNo Then GoTo Skip
If Answer = vbYes Then
'It's benny, lets just double check'
Answer = MsgBox("Are you absolutely sure!", vbQuestion + vbYesNo, "Delete
Patient Record - AYS")
If Answer = vbNo Then GoTo Skip
If Answer = vbYes Then
ActiveSheet.Delete
Sheets("Menu").Select
MsgBox "*Patient Record has been deleted - If done in error please use
previous document version*"
End If
End If
Skip:
Sheets("Menu").Select
End Sub
Basically, when the user submits a "no" response to the Answer msg box under sub DeleteRecord() the code currently brings it back to sub deletepatientcheck and goes to the msg box "No Patient Record found" . This happens even when a record is found.
What I am trying to do is if a no response is given then bring up a different message box saying "Delete request cancelled" instead of the MsgBox "No Patient Record Found!". But no matter what IF/then function or Skip: i use it always displays the "No patient record found" msg box. Can anyone help? happy to explain further if required. Thanks in advance.
This should work for you. Check the value of Boolean variable Exists before displaying your MsgBox.
Sub 1:
Sub DeletePatientCheck()
'check if patient record exists before deleting'
Dim s As Worksheet
On Error Resume Next
'Check if Patient Record already exists'
Dim Exists As Boolean
For Each s In Sheets
If s.Name = Selection Then
Worksheets(s.Name).Activate
Call DeleteRecord
Exists = True
End If
Next s
If Not Exists Then MsgBox "*No Patient Record Found!*"
End Sub
Sub 2: (Recommendations) You can avoid coding the vbNo by just coding for vbYes, and using the Else statement to address the vbNo.
Also notice that you can avoid using the GoTo Skip: method by just calling the task immediately and then using Exit Sub. This link goes into further detail about Goto.
Sub DeleteRecord()
'Confirm delete?'
Dim Answer As String, Answer1 As String
Answer = MsgBox("Are you sure you want to delete this Patient Record?", vbQuestion + vbYesNo, "Delete Patient Record")
If Answer = vbYes Then
Answer1 = MsgBox("Are you absolutely sure!", vbQuestion + vbYesNo, "Delete Patient Record - AYS")
If Answer1 = vbYes Then
ActiveSheet.Delete
Sheets("Menu").Select
MsgBox "*Patient Record has been deleted - If done in error please use previous document version*"
Else
MsgBox ("Delete Request Cancelled")
Sheets("Menu").Select
Exit Sub
End If
Else
MsgBox ("Delete Request Cancelled")
Sheets("Menu").Select
Exit Sub
End If
End Sub

BeforeClose will not close my Excel-Sheet VBA

So I have been trying to put together a little Excel sheet, that has an entry Log in it. So whenever the sheet is closed, Name, Date and Time are added.
So basically I have three macro running, I will only mention two. The main macro will ask if I want to close the sheet and I will have to answer with yes or no. This works fine. If I press yes the main macro will call a sub macro, that will ask me to enter a string. If this Inputbox is empty or the entry is canceled, I want the main sub to stop running and cancel the Close process. Which won't seem to work. The error in the code to me seems pretty clear, but I don't know how to prevent it and find a better solution. If you could help me come up with a solution I would really appreciate it.
This line of code seems to be the problem:
If Cancel_Button_LOG = False Then Cancel = True
Here I will add compressed versions of the two macros
Public Sub Add_Entry_to_Log()
Dim i As Integer
Dim response As Variant
Cancel_Button_LOG = True
response = InputBox("Please enter your Name", "Name")
If response <> "" Then
Else
Cancel_Button_LOG = False
MsgBox "Please enter your name", vbExclamation + vbOKOnly, "Name"
End If
Worksheets("Log").Protect "secret"
ThisWorkbook.Save
End Sub
Now I will want to use the Cancel_Button_log Variable to cancel the main sub:
Dim answer As Variant
answer = MsgBox("Are your sure you want to close the workbook?", vbYesNo) Cancel = False
Select Case answer
Case Is = vbYes
Worksheets("Log").Unprotect "secret"
Call Test
Call Add_Entry_to_Log
If Cancel_Button_LOG = False Then Cancel = True
Worksheets("Log").Protect "secret"
Case Is = vbNo
Cancel = True
End Select
ThisWorkbook.Save
End Sub
I think you're doing this in the most complicated way possible. If I understand your requirements correctly - you can replace all your code in your ThisWorkbook module with something like this:
Const WB_LOG As String = "Log" '// name of sheet that the log is in
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If MsgBox("Do you really want to close the workbook?", vbYesNo) = vbYes Then
With Sheets(WB_LOG)
.Range("A" & .Rows.Count).End(xlUp).Offset(1, 0).Resize(1, 2).Value = Array(Environ$("USERNAME"), Now)
End With
ThisWorkbook.Save
Else
Cancel = True
End If
End Sub
Private Sub Workbook_Open()
With Sheets(WB_LOG)
.Protect Password:="secret", UserInterfaceOnly:=True
.Range("A1:B1").Value = Array("USERNAME", "TIMESTAMP")
End With
End Sub
This would negate the need for the user to manually insert their name (assuming their system username would suffice*) and also negate the need to unprotect the worksheet each time as I've used the UserInterfaceOnly option.
* Environment variables such as %USERNAME% can be falsified if a user wishes to do so and knows how - however someone typing their name into a textbox is even easier to falsify...

Why does this vba MsgBox always return zero?

I have a VBA MsgBox with vbYesNo as the button-type but no matter what button is pushed it always shows a return result as zero. Sorry this isn't the entire code but the below code is a portion of the code that is giving me trouble.
Sub testMsg()
Dim strCheckFolders As Integer ' <== vbyesno MsgBoxResult (7 = no, 6 = yes)
Dim RunThis As Boolean
RunThis = True
Do Until RunThis = False
If strCheckFolders = MsgBox("Do you want to check folders for reports to print?", _
vbYesNo, "Check for Reports to Print") = vbNo Then RunThis = False
Loop
End Sub
Basically what I'm trying to do is write this loop without using the standard phrase if x=vbNo then Exit Sub. I'd rather try to let it run it's course. But that would only work if MsgBox could change the value of RunThis to False.
Any help is really appreciated.
= is used both as an assignment operator and a comparison operator in VBA. You can't assign and compare in a single statement (at least not without the unexpected results you're getting). Separate the assignment from the comparison:
Do Until RunThis = False
strCheckFolders = MsgBox("Do you want to check folders for reports to print?", vbYesNo, "Check for Reports to Print")
If strCheckFolders = vbNo Then RunThis = False
Loop
You could even remove the need for strCheckFolders altogether:
Do Until RunThis = False
If MsgBox("Do you want to check folders for reports to print?", vbYesNo, _
"Check for Reports to Print") = vbNo Then RunThis = False
Loop
I would place the MsgBox in an if statement. Then based on the result do an action
Do Until RunThis = False
If MsgBox("Do you want to check folders for reports to print?", vbYesNo) = vbNo Then
RunThis = False
End If
Loop
End Sub

Read-Only and undo properties MS Access (VBA)

I have been surfing the wed looking for an answer to what I thought it was a pretty simple question, for a newbie like me.. But havent found any so here I am!. To keep things simple, i'll attach the two bits of my code that are giving me a bit of a headache. What I intend to do is to switch from a Read-Only mode to a Write Allowed state by clicking a button. In order to do so, I want the routine to check for changes on the record and, if there are any ask the user to decide whether to save the changes or discard them.. While testing this particular button, I found out something quite "funny".. It seems to work well when no changes are introduced. Switches perfectly from read-only to write-allow states. However, when in write-allow and changes have been made, if the "Save option" has been selected/clicked then it does not lock the content although all the other subroutines and changes are implemented.
My other problem, closely related to this, is that I cant find a way to set a "saving point" for the undo option. I would like to find a way to "save a record" so when the undo button is pressed doesnt undo all the changes that the record has suffered since the database has been firstly opened (as its currently happening), but since the button has been pressed. I tried the DoCmd Save function but is not behaving as I was expecting (Note: the last 'else' has been my last try to this problem but, again, its not working as expected)
Many thanks for all your future collaboration,
Alex
Private Sub Command28_Click()
If Form_AODNewRecord.AllowAdditions = True Then
Call isModified_Save
Form_AODNewRecord.AllowAdditions = False
Form_AODNewRecord.AllowEdits = False
Form_AODNewRecord.AllowDeletions = False
MsgBox "Read Only. Addition, Edits and Deletions are now locked"
Command28.Caption = "LOCKED"
Else
Form_AODNewRecord.AllowAdditions = True
Form_AODNewRecord.AllowEdits = True
Form_AODNewRecord.AllowDeletions = True
MsgBox "New records, edits and deletions are now allowed"
Command28.Caption = "Lock mode OFF"
End If
MsgBox Form_AODNewRecord.AllowAdditions
End Sub
Sub isModified_Save()
If Form_AODNewRecord.Dirty Then
Dim strMsg As String, strTitle As String
strMsg = "You have edited this record. Do you want to save the changes?"
strTitle = "Save Record?"
If MsgBox(strMsg, vbQuestion + vbYesNo, strTitle) = vbNo Then
Me.Undo
Else
DoCmd.OpenTable "AOD Type", acViewPreview, acReadOnly
DoCmd.Save acTable, "AOD Type"
DoCmd.Close acTable, "AOD Type", acSaveYes
End If
End If
End Sub
I think you want the following code. You cannot open a table that the form is bound to and affect the form, when you open the table, you have two different instances and they do not affect one another.
An odd side effect of running a macro in Office applications is that it clears the Undo list, so I created a small macro that just shows a message "Undo cleared" and that is exactly what it does!
As an aside, rename your control with meaningful names, such as cmdLock, rather than Command28, you will thank yourself later.
Private Sub Command28_Click()
If Me.AllowAdditions = True Then
Call isModified_Save
Me.AllowAdditions = False
Me.AllowEdits = False
Me.AllowDeletions = False
MsgBox "Read Only. Addition, Edits and Deletions are now locked"
Command28.Caption = "LOCKED"
Else
Me.AllowAdditions = True
Me.AllowEdits = True
Me.AllowDeletions = True
MsgBox "New records, edits and deletions are now allowed"
Command28.Caption = "Lock mode OFF"
End If
''MsgBox Me.AllowAdditions
End Sub
Sub isModified_Save()
If Me.Dirty Then
Dim strMsg As String, strTitle As String
strMsg = "You have edited this record. Do you want to save the changes?"
strTitle = "Save Record?"
If MsgBox(strMsg, vbQuestion + vbYesNo, strTitle) = vbNo Then
Me.Undo
Else
''Save record
Me.Dirty = False
''Clear undo list
DoCmd.RunMacro "ClearUndo"
End If
End If
End Sub