问题
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
回答1:
Please follow these steps:
- Insert a new Form by right-clicking on your VBA project and selecting
UserForm
under theInsert
option. - Click once on the created form and then press the ``F4
key to open the
Properties``` window. - On the
Properties
window, the default name for your form isUserForm1
. Change it to any new value as you want (e.g., WarningBox) - From the
ToolBox
window, drag and drop aLabel
on your form and adjust its size, font, font color, and all other properties that exist on theProperties
window. Please rename the label tomessage
. I will use this name later when calling the form to be shown. - If you want, like step 4, add a
CommandButton
to your form and change its name to for exampleokButton
and adjust other properties as you want. - 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
- 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!
回答2:
Marc: if your "Incorrect" message is the "LOL" object whose caption you modify with the code form.LOL.Caption = "INCORRECT!"
, it will be editable if it is a TextBox object. Saeed Sayyadipour's example shows using a Label object, instead, that will not be editable by the user (and I 'second' his advice about the "OK" button).
Also, though, since the event tells you which cells were changed by defining the "Target" range object, do you really need to loop through all of G4:G160, since only the cells within Target were changed by the user? Perhaps use For Each MyCell in Intersect(Target,Range("G4:G160"))
, or perhaps add these lines where appropriate:
Dim AffectedCells as Range
...
Set AffectedCells=Intersect(Target,Range("G4:G160"))
...
Set AffectedCells=Nothing
and change your loop to:
For Each myCell in AffectedCells
...
Next myCell
If there is no overlap between the changed range (Target) and your G4:G160, nothing happens and your code exits quickly.
来源:https://stackoverflow.com/questions/62279174/how-to-add-userform-into-this-code-instead-of-msgbox