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
Related
I've looked all over for the solution to this, finally figured I would just ask.
I have a form I've created in Word. It is not a formal "userform1" type form as in a VB project. It is written all in the Word document itself.
I am going to have a lead person email my this report every evening. I have been able to successfully have the user click the submit button and email the form (MS Word (NighlyReport.DOCM)).
In the final stages now, I am "trying with no success" to validate all of my textboxes with no luck.
I want to make each textbox required and if the user does not enter a value, I would like the "setFocus" to return the user back to the textbox. Since I am not using an official "userform" I do not seem to have this method available to me - to return the user back to the form. I have tried
_Change
_GotFocus
_LostFocus
_KeyPress
_MouseDown
All of these work fine as long as I am inside the textbox. None of them sends the user back to it.
Does anybody know a way to do this. I wanted a straightforward nice looking form to fill out and attach to outlook (which I've done). Just need to validate the textboxes. I would be willing to validate all of them with a commandbutton as well, but still cannot get the focus back to the textbox that was not filled out by the user.
For the sake of simplicity, I am posting just two textboxes here and my basic validation that is not working. To be clear, I am not using the userform grid, maybe that makes all of this impossible to do.
Thanks ahead:
Private Sub txt1_Change()
If txt1.Value = "" Then
MsgBox "need your input"
Else
Exit Sub
End If
End Sub
Private Sub txt2_Change()
If txt2.Value = "" Then
MsgBox "need your input"
Else
Exit Sub
End If
End Sub
Try something along the lines of:
Dim iShp As InlineShape, StrOut As String
For Each iShp In ActiveDocument.InlineShapes
With iShp
If .Type = wdInlineShapeOLEControlObject Then
If .OLEFormat.ClassType Like "Forms.TextBox.*" Then
If Trim(.OLEFormat.Object) = "" Then StrOut = StrOut & vbCr & .OLEFormat.Object.Name
End If
End If
End With
Next
If StrOut <> "" Then
MsgBox "The following controls have not been completed: " & StrOut
Exit Sub
End If
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.
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)
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
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