Msgbox Invalid Outside Procedure - vba

I have a problem in VBA(so I'm new).
I have a error with this code
Dim Msg, Style, Title, Help, Ctxt, Response, MyString
Msg = "Do you want to continue ?" ' Define message.
Style = vbYesNo + vbCritical + vbDefaultButton2 ' Define buttons.
Title = "MsgBox Demonstration" ' Define title.
Help = "DEMO.HLP" ' Define Help file.
Ctxt = 1000 ' Define topic context.
' Display message.
Response = MsgBox(Msg, Style, Title, Help, Ctxt)
If Response = vbYes Then ' User chose Yes.
MyString = "Yes" ' Perform some action.
Else ' User chose No.
MyString = "No" ' Perform some action.
End If
Error: Invalid outside procedure
Can you help me :))?

Write Sub Test() before the code... And ... End Sub after the code and then run it.
You can refer to Sub statement

Related

Is there any way to change the properties of a Ms Access dialog Form when is Opened?

Instead of using msgBox, I want to create My msgBox by form, "frmMsg".
"frmMsg" form has tow bottom, (Ok and No), and a label(lblMsg) for show message.
"frmMsg" property: Pop Up = Yes , Modal = Yes.
My Function for Open form is MsgInfo:
Public Function MsgInfo(Optional msg As String = "Are You Ok?", _
Optional msgCaption As String = "Warning" ) As Boolean
MsgInfo = False
DoCmd.OpenForm "frmMsg"
Form_frmMsg.Caption = msgCaption ' Set Caption of Form
Form_frmMsg.lblMsg.Caption = msg ' Set Message of Form
MsgInfo = MsgInfoResult ' MsgInfoResult is Public Variable to store MsgInfo Result (Ok Bottom(True) or No Bottom(False) )
End Function
I used this in other Form, Example For delete Customer in Customer List ( Delete Bottom ):
Private Sub btnDelete_Click()
DoCmd.SetWarnings False
If MsgInfo("Are You Sure Delete Customer?", , "Delete Customer!") = True Then
' Run SQL for Delete Customer
Dim sqlDelete As String
sqlDelete = "DELETE tblCustomer.*, tblCustomer.RowId " & _
"FROM tblCustomer " & _
"WHERE tblCustomer.RowId=[Forms]![frmCustomerList]![frmCustomerListSub]![RowId]"
DoCmd.RunSQL sqlDelete
Form_frmCustomerList.frmCustomerListSub.Requery
End If
DoCmd.SetWarnings True
End Sub
My Problem is After Open MsgInfo Form Before the user answers this, the Next commands (Sql) are executed.
To solve the problem, I changed AcWindowsMode in Function MsgInfo:
DoCmd.OpenForm "frmMsg"
to
DoCmd.OpenForm "frmMsg", , , , , acDialog
problem solved but There was another problem. The following commands are not executed:
Form_frmMsg.Caption = msgCaption ' Set Caption of Form
Form_frmMsg.lblMsg.Caption = msg ' Set Message of Form
MsgInfo = MsgInfoResult ' MsgInfoResult is Public Variable
please help me.
I am no Expert in VBA or Any Programming Language neither am I a programmer by Profession. But , I've had my fair share in dealing with programming languages as a hobby.
In VBA, Any Code after the ,,,,,acDialog can't be run until the Form is closed so , What you need to do is find a way to Pass the Messages somewhere and have the form Retrieve it.
Create a Module to Pass the Message from the Function to the Form
'a Module named Module_gVar
Public MessageHeader as String 'Optional A Separate Text Box For a Header
Public MessageBody as String 'Main Body
Public MessageTitle as String 'Caption of the Form
Public MessageReturn as Boolean
This is the function to Call the Message box and Get a simple True or False Return
'Function To Call the MessageBox
Public Function CallMessageBox ( _
Optional msgHeader as string , _
Optional msgBody as string , _
Optional msgTitle as string)
Module_gVar.MessageTitle = msgTitle
Module_gVar.MessageHeader = msgHeader
Module_gVar.MessageBody = msgBody
DoCmd.OpenForm "frmMessage",,,,,acDialog
CallMessageBox = Module_gVar.MessageReturn
'You can have the CleanUp on a Separate Function
'Since it's not a Procedure Variable it Isn't cleaned when it goes out of scope
Module_gVar.MessageTitle = ""
Module_gVar.MessageBody = ""
Module_gVar.MessageHeader = ""
Module_gVar.Return = False
End Function
Now for the Form itself.
'Retrieve the Strings
Private Sub Form_Current()
Me.[YourHeaderTextBox] = Module_gVar.MessageHeader
Me.[YourBodyTextBox] = Module_gVar.MessageBody
Me.Caption = Module_gVar.MessageTitle
End Sub
'A Button to Return a Value
Private Sub cmdYes_Click() ' Yes button
Module_gVar.MessageReturn = True
DoCmd.Close acForm,"frmMessage",acSaveNo
End Sub
Private Sub cmdNo_Click() ' No Button
Module_gVar.MessageReturn = False
Docmd.Close acForm,"frmMessage",acSaveNo
End Sub
You can Optimize the code from here on but it's the basic structure. I Recommend creating a Class Module in which you can retrieve strings , input strings , and call Forms.

Error Code 424 when trying to set a value based on a message box response

I have been trying to get this to work but I do not see the issue with it.
My form is called "Request_Order" and the Yes/No checkbox is called "Processed"
Private Sub MarkProcessedOrig_Click()
Const cstrPrompt As String = _
"Are you sure you want to mark this request as processed? Yes/No"
If MsgBox(cstrPrompt, vbQuestion + vbYesNo) = vbYes Then
Request_Order.Controls(Processed).Value = True
Else: Cancel = True
End If
End Sub
Your syntax is wrong. Collection elements are identified by the name of the element, which is a string, or by the offset, which is an integer. So you need to do this:
Request_Order.Controls("Processed").Value = True
The error you're getting is that the VBA runtime can't parse your statement as an object, because your code is saying that there's a variable called Processed that evaluates to a string, and that that variable is a assigned a string value that is the name of one of the controls in your collection. Since that isn't true, you get this error.
Need to delete ‘Request_Order’, this is not necessary, it will run successfully after deletion.
Please try the code below:
Private Sub CommandButton1_Click()
Const cstrPrompt As String = _
"Aref'jei you sure you want to mark this request as processed? Yes/No"
If MsgBox(cstrPrompt, vbQuestion + vbYesNo) = vbYes Then
Controls("CheckBox1").Value = True
Else: Cancel = True
End If
End Sub

Excel Macro YesNo message box, different directions for Yes and No

The user has two options in the YesNo Message Box. If No, it performs a certain sequence of filters, but I want to filter another column if the user answers Yes to the message box question. Currently, at "Else", I get an error that reads "Compile error: Function call on left-hand side of assignment must return Variant or Object" If I take out "Else", and the code after it, the macro runs smoothly, but only filters when the user selects No.
If MsgBox("Is This Item Catch Weight?", vbYesNo) = vbNo Then
retval = InputBox("Please Enter PO Cost")
ActiveSheet.Range("$A$1:$CL$293662").AutoFilter Field:=71, Criteria1:="=" & retval
retval = InputBox("Please Enter Net Weight")
ActiveSheet.Range("$A$1:$CL$293662").AutoFilter Field:=41, Criteria1:="=" & retval
Else: MsgBox("Is This Item Catch Weight?", vbYesNo) = vbYes
retval = InputBox("Please Enter PO Cost")
ActiveSheet.Range("$A$1:$CL$293662").AutoFilter Field:=71, Criteria1:="=" & retval
End If
End If
A few things are happening here. : new line character in VBA code so a line like
Else: MsgBox("Is This Item Catch Weight?", vbYesNo) = vbYes
is actually the same as
Else
MsgBox("Is This Item Catch Weight?", vbYesNo) = vbYes
Which is not what you want.
There is also an extra End If at the end. Remove that.
Calling the message box to appear multiple times is probably not what oyu want either. Likely you want to show the message box, get the result then do something with it.
Dim response As VbMsgBoxResult
response = MsgBox("Is This Item Catch Weight?", vbYesNo)
If response = vbNo Then
'do stuff for yes
ElseIf response = vbYes Then
' do stuff for No
End If
I'd also suggest not using ActiveSheet unless you are sure that's what you want.

Visual Basic: Message Box Prompt Twice When I Click On Button

I have problem with my message box. This is part of app which check if serial number has already been used. If yes, it shows error message,when click YES program continues and make some functions, NO button end sub. It works well, but it shows me message box twice and I really don't understand why, please help
If File.Exists(pathSN) Then
Dim Findstring = IO.File.ReadAllText(pathSN)
If Findstring.Contains(Lookfor) Then
Dim msg = "Serial number has already been used"
Dim title = "Error"
Dim style = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or _
MsgBoxStyle.Critical
Dim response = MsgBox(msg, style, title)
MsgBox(msg, style, title)
If response = MsgBoxResult.Yes Then
wrlayout()
openlayout()
Exit Sub
Else
Exit Sub
End If
End If
End If
...
Dim response = MsgBox(msg, style, title)
MsgBox(msg, style, title)
...
you do not need the second call to MsgBox

Looping through a collection of text boxes

I have a userform that has three conceptual groups of textboxes. I'm trying to create a collection for each group and then when the user clicks on a button to call a sub/function associated with one of those groups, I want to be able to call a function that loops through the collection of textboxes associated with that group and check if they are empty, contain invalid characters, etc.
I've made the following declarations at the module level.
Dim typSectFields, laneFields, matFields As Collection
Then when the user form initializes I add the text boxes to the collections:
Set typSectFields = New Collection
With frmAddTypSect
typSectFields.Add txtTypSectName
typSectFields.Add txtStartSta
typSectFields.Add txtEndSta
End With
And then when the user clicks the button that uses the input from the "typSectFields" collection:
Dim tb As Control, res As VbMsgBoxResult
For Each tb In typSectFields
If tb.Text = vbNullString And t.Tag <> vbNullString Then
res = MsgBox("You've not completed the " + tb.Tag + " field. Would you like to complete it now?", vbYesNo + vbQuestion)
If res = vbYes Then Exit Sub
End If
Next
I get an "Object Required" error when execution hits the For loop.
VBE shows that tb = nothing and typSectFields = Empty.
What am I doing wrong?
Make sure all of your code (specifically the module-level declarations) are in the code behind the form module. The following runs without error for me:
Dim typSectFields As Collection, laneFields As Collection, matFields As Collection
Private Sub CommandButton1_Click()
Dim tb As Control, res As VbMsgBoxResult
For Each tb In typSectFields
If tb.Text = vbNullString And tb.Tag <> vbNullString Then
res = MsgBox("You've not completed the " + tb.Tag + " field. Would you like to complete it now?", vbYesNo + vbQuestion)
If res = vbYes Then Exit Sub
End If
Next
End Sub
Private Sub UserForm_Initialize()
Set typSectFields = New Collection
With frmAddTypSect
typSectFields.Add txtTypSectName
typSectFields.Add txtStartSta
typSectFields.Add txtEndSta
End With
End Sub