Search code examples
vbauserformmsgbox

How to add userform into this code instead of msgbox?


I currently have this code

Private Sub Worksheet_Change(ByVal Target As Range)
Dim myCell As Range

For Each myCell In Range("G4:G160")

    If (Not IsEmpty(myCell)) And myCell.Value <> 17521 And myCell.Value <> "" Then

        DisplayUserForm

        Exit Sub
    End If

Next myCell
End Sub

and have this for my userform

Sub DisplayUserForm()

Dim form As New WarningBox
form.LOL.Caption = "INCORRECT!"
form.Show
Set form = Nothing

End Sub

What else must I do in order for this to appear instead of msgbox to alert whoever is entering data will be showing "INCORRECT!" in bold and Surrounded by red. Please see image below of what I am trying to show enter image description here


Solution

  • Please follow these steps:

    1. Insert a new Form by right-clicking on your VBA project and selecting UserForm under the Insert option. enter image description here
    2. Click once on the created form and then press the ``F4key to open theProperties``` window. enter image description here
    3. On the Properties window, the default name for your form is UserForm1. Change it to any new value as you want (e.g., WarningBox)
    4. From the ToolBox window, drag and drop a Label on your form and adjust its size, font, font color, and all other properties that exist on the Properties window. Please rename the label to message. I will use this name later when calling the form to be shown. enter image description here
    5. If you want, like step 4, add a CommandButton to your form and change its name to for example okButton and adjust other properties as you want. enter image description here
    6. Double click on the button to write the code for this button. Write the code as follows:
    Private Sub okButton_Click()
    
        'Close the form
        Unload Me
    End Sub
    
    1. Now, modify your DisplayUserForm() sub as follows:
    Sub DisplayUserForm()
    
        Dim form As New warningBox
        form.message.Caption = "write your message here"
        form.Show
        Set form = Nothing
    
    End Sub
    

    All will be done as you want!