VBA Access Message Box woes - vba

I followed a few simple comments on how to pop a confirmation box before executing a script, but sadly, if I press yes, the script doesn't run.
Private Sub Overwrite_Btn_Click()
If MsgBox("Yes?", vbOKCancel) = ok Then
Me.Product_Quantity = Me.Quantity_Input
Else
Exit Sub
End If
End Sub
I'm trying to set Product_Quantity equaling Quantity_Input, and although it works without the MsgBox command, it doesn't with it.
What am I doing wrong?

Instead of If MsgBox("Yes?", vbOKCancel) = ok Then try: If MsgBox("Yes?", vbOKCancel) = vbOK Then
Typically the interactions with forms will return one constant from a set of several constants. Those are catalogged in enums. In this case you have several constants in the VbMsgBoxResult class, and vbOK is a constant with value 1, which is returned from clicking the ok button.
Actually, If MsgBox("Yes?", vbOKCancel) = 1 Then would work as well, but it is harder to remember that clicking Ok returns 1 then simply stating a constant named vbOK
In object explorer (F2 on the VBE), searching for VbMsgBoxResult will give all possible results that comes from interacting with a message box.

https://www.techonthenet.com/access/constants/msgbox_ret.php
1) Dim a variable as integer.
2) Check for value of integer equal to 6, or check for vbYess
3) ?????
4) Profit
borrowed from link
Dim LResponse As Integer
LResponse = MsgBox("Do you wish to continue?", vbYesNo, "Continue")
If LResponse = vbYes Then
{...statements...}
Else
{...statements...}
End If

Single line:
If MsgBox("Yes?", vbOKCancel) <> vbOk then Exit Sub
'continue code here.
More Information:
MSDN : MsgBox Function (Office/VBA)

Related

What property will return the caret (or cursor type bar) to the designated textbox in VBA Excel UserForms? [duplicate]

I have a textbox on a userform. If the user fails to enter anything in this textbox, I need to trap that to force an entry. I can do this easily enough, but after notifying the user tht they need to make an entry, I want the focus to return to the textbox. Right now, it doesn't do that. Here is my code:
Private Sub txtAnswer_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Select Case KeyCode
Case 13:
If Me.txtAnswer.Value = "" Then
temp = MsgBox("You need to enter an answer!", vbCritical + vbOKOnly, "No Answer Found!")
Me.txtAnswer.SetFocus
Else
recordAnswer
End If
End Select
End Sub
This code works fine in that the message box pops up if the textbox is left blank. After clearing the message box, if I hit enter immediately again, the message box reappears, suggesting that the focus is on the textbox. However, if I try to enter a character (like the number '1' for example) nothing appears in the textbox.
Can anybody suggest how I can get the focus back on this textbox in a way that will allow the user to enter data? Thank you!
Why are you not using an 'ok' button to complete the action?
You should not bother users with messages while they are typing in a form. Do it at the end.
Private Sub OK_Click()
'// Validate form
If txtAnswer.Text = vbNullString Then
MsgBox "You need to enter an answer!", vbExclamation, "No Answer Found!"
txtAnswer.SetFocus
Exit Sub
End If
'// You have reached here so form is correct carry on
recordAnswer
End Sub
If you really want to use the behaviour you asked for then try this:
Private Sub txtAnswer_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Select Case KeyCode
Case 13:
If Me.txtAnswer.Value = "" Then
temp = MsgBox("You need to enter an answer!", vbCritical + vbOKOnly, "No Answer Found!")
KeyCode = 0
Else
recordAnswer
End If
End Select
End Sub
The problem is that in your code you are setting focus but the enter key is firing afterwards. You don't need to set focus because the textbox already has the focus you just need to cancel the enter key.
The other answers seem really complicated. I had a similar problem and really wanted a text warning. It seemed easier for me to just make an invisible label on the form that would show up if the input was incorrect. I also made the background of the label red so that the user would notice something was wrong. Doing it this way kept the cursor visible and right where they left off.
Public Function amount(ByRef cont As MSForms.TextBox) As Integer
'makes sure that a number is used
'could change to account for decimals if necessary
Dim i As Long
On Error Resume Next
i = 0
If (cont.Value = "") Then Exit Function
Do While i < 1000000
If (cont.Value = i) Then
UserForm1.Label257.Visible = False
Exit Function
End If
i = i + 1
Loop
UserForm1.Label257.Visible = True
amount = 1
End Function
Public Sub qty_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
If amount(UserForm1.qty) = 1 Then
Cancel = True
End If
End Sub
I hope this helps other who run into this problem later on.
Looking at the above code, I assume the i counter is to keep it going? Sorry a bit rusty, been a few years since I've done code.
At any rate, if thats the case you could always run it while i=0, do (or while true).
Sorry, first time posting here, hope that made sense.

Command Button in msgbox vba possible?

si it possible to add a command button in the msgbox window in vba?
For example, i want to add a cancel button that stops the code rather than continuing it. I could create a new userform, but it would be nice if i save some space and use the msgbox that is already here.
VBA has several different types of MessageBoxes with built in command buttons for this very purpose. The type of buttons included in the message box is declared as the second parameter - MsgBox(Prompt, Buttons as)
The types you are probably interested in are:
vbYesNo
vbYesNoCancel
vbAbortRetryIgnore
vbOkCancel
vbRetryCancel
These Buttons return integer values that need to either be stored or used for comparison.
VBA has these integer answers stored as constants (e.g. vbOK = 1, VbCancel = 2, etc.) See Microsoft Developer Network MsgBox Function for more details on that.
Sub mySub()
Dim answer as Integer
answer = MsgBox("Would you like to choose yes?", vbYesNoCancel)
If answer = vbYes Then
'Do whatever you want
ElseIf answer = vbNo Then
'Do whatever
Else
Exit Sub
End If
End Sub
Try this:
If MsgBox("Cancel or Continue, are you sure?", vbOKCancel) = vbOK Then
'continue whatever you want to do.
End if

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...

VBA : vbYesNo displays a button with OK and nothing else

Title speaks for itself.
Here is an illustration
and here is the line of code I'm using.
If MsgBox("Are you sure?", vbYesNo) = Yes Then Exit Sub
I'm also using EXTRA! X-treme
I'd have to guess that EXTRA! X-treme (wow! hyperbole much?!) is messing with the vb constants, or at least not respecting them if it is intercepting calls to the MsgBox function.
vbYesNo should be a constant numeric value of 4.
Also, instead of comparing the result of MsgBox to Yes, you should probably be comparing it to vbYes (numeric value of 6).
I think you're using VBA correctly (except for the vbYes part), so this might be an EXTRA! X-treme bug (or under-documented feature).
Solution
If MsgBox("Are you sure?", 4) = 6 Then Exit Sub
If DialogResult.OK = Windows.Forms.MessageBox.Show("Are You Sure ? ", "Choose Folder",System.Windows.Forms.MessageBoxButtons.OK,System.Windows.Forms.MessageBoxIcon.Question) Then
' Do Code
End If

Understanding what response codes come back from MsgBox

I'm very new to programming and I'm just starting to learn VBA with excel. I came across on this website and did the examples here but I have question about this code:
I know the variables are declared using "Dim" statement "Message" here is the variable with a data type of integer. What I don't clearly understand is; what is the meaning of "6" here and "7". I believe they come from somewhere. But as I just started learning this program, I don't have any idea. Could you please tell me how it end up to "6" and "7". I believe there is some basis here
Private Sub CommandButton1_Click()
Dim message As Integer
message = MsgBox("Click Yes to Proceed, No to stop", vbYesNoCancel, "Login")
If message = 6 Then
Range("A1").Value = "You may proceed"
ActiveWorkbook.Activate
ElseIf message = 7 Then
ActiveWorkbook.Close
End If
End Sub
Thank you for your help:-)
=======
Thanks guys for the answers, they're very helpful. Yes this thread has been already posted in superuser site. I was informed that this question should belong here so I posted it here after reading that they will do it automatically from superuser to stackoverflow.
thanks once again
MsgBox does return an Enum(eration) called MsgBoxResult, which is basically nothing else then numeric values with a 'label'. 6 and 7 in this case are members of this enum, which are mapped to the answers Yes and No.
Using so called 'magic numbers' instead of Constants or Enums should avoided whenever possible.
Basically, you could rewrite the code to this:
Dim message As Integer
message = MsgBox("Click Yes to Proceed, No to stop", vbYesNoCancel, "Login")
If message = MsgBoxResult.Yes Then
Range("A1").Value = "You may proceed"
ActiveWorkbook.Activate
ElseIf message = MsgBoxResult.No Then
ActiveWorkbook.Close
End If
Might be that the Enum is called vbMsgBoxResult or something... I don't have an Office to verify this, just Visual Studio.
While we are on it... this might be easier to understand:
Select Case MsgBox("Click Yes to Proceed, No to stop", vbYesNoCancel, "Login")
Case MsgBoxResult.Yes
Range("A1").Value = "You may proceed"
ActiveWorkbook.Activate
Case MsgBoxResult.No
ActiveWorkbook.Close
Case MsgBoxResult.Cancel
' he clicked cancel '
End Select
When I first started with MsgBox answers, I almost always declared the answer as an Integer. However, I learned that the best thing to do is to declare your message variable as VbMsgBoxResult, which is an enumeration that will always show the available answers. In the picture below, the IDE (e.g. the Visual Basic for Application editor) will show you the possible options available in VbMsgBoxResult.
You could store your answer variable as an Integer since all of the variables in the Enumeration (e.g. vbAbort, vbYes, vbOK, etc.) do in fact resolve to integers. However, you have to figure out what the integer values for those variables are every time you want to reference them. In my opinion, it's a better practice to store your answer as VbMsgBoxResult so you can actually see the available answers.
It's very poorly written code, "6" and "7" are the values of the constants "vbYes" and "vbNo" where are returned when the user clicks Yes or No on the dialog.
Reference: http://www.techonthenet.com/access/constants/msgbox_ret.php
The code should say
If message = Constants.vbYes
instead of
If message = 6
So that it is clear what is happening.
This link is for VBScript, but I think the return codes should be the same:
MsgBox Function Reference
The Return Codes tell you which button was clicked:
1 OK
2 Cancel
3 Abort
4 Retry
5 Ignore
6 Yes
7 No
These are return value from MsgBox(). The author should have used their symbolic value instead to make the program more readable:
vbYes 6
vbNo 7
See this MSDN article for more info
6 and 7 are the return codes from the MsgBox method. Basically, when MsgBox is called, it shows a message-box to the user, who clicks either "Yes", "No", or "Cancel". The user's selection is returned from the MsgBox method as a number, where 6 is Yes, and 7 is No.
It is considered best-practice not to use these numbers in your code directly, but instead to use Microsoft supplied constants which represent them. Your code could be re-written as:
Private Sub CommandButton1_Click()
Dim message As Integer
message = MsgBox("Click Yes to Proceed, No to stop", vbYesNoCancel, "Login")
If message = vbYes Then
Range("A1").Value = "You may proceed"
ActiveWorkbook.Activate
ElseIf message = vbNo Then
ActiveWorkbook.Close
ElseIf message = vbCancel Then
'Do nothing.
End If
End Sub
The 6 and 7 are hard coded values that hold a special meaning. The 'MsgBox("Click Yes...")' call will return a number that will let your code determine what the user did with the message box and you can then use conditionals (your IF statements) to decide what to do next.
A full list of these special values can found in the MSDN documentation here:
http://msdn.microsoft.com/en-us/library/139z2azd(VS.80).aspx
Just rewrite to the equivalent:
Private Sub CommandButton1_Click()
Dim optionSelected As VbMsgBoxResult
optionSelected = MsgBox("Click Yes to Proceed, No to stop", vbYesNoCancel, "Login")
If optionSelected = vbYes Then
Range("A1").Value = "You may proceed"
ActiveWorkbook.Activate
ElseIf optionSelected = vbNo Then
ActiveWorkbook.Close
End If
End Sub
And move on