Excel VBA 中的对话框(Dialog Boxes)用于向用户显示信息。
MsgBox 函数在对话框中显示一条消息,等待用户单击按钮,并返回一个整数指示用户单击了哪个按钮。
最常用的对话框是消息框,但我们也可以使用输入框。
到目前为止,我们已经使用MsgBox对话框在屏幕上显示信息。
Sub delete_B2()
Range("B2").ClearContents
MsgBox "The contents of B2 have been deleted !" '“B2单元格的内容已被删除!”
End Sub
在这种情况下,仅使用一个参数调用 MsgBox。看代码如下:
现在我们将创建一个对话框,在执行两条指令之前要求确认删除。然后我们将使用三个参数:
MsgBox([文本]、[按钮]、[标题])
Sub delete_B2()
If MsgBox("Are you sure that you wish to delete the contents of B2 ?", vbYesNo, "Confirm") = vbYes
Then
Range("B2").ClearContents
MsgBox "The contents of B2 have been deleted !"
End If
End Sub
结果:
Private Sub warning(var_text As String)
MsgBox "Caution : " & var_text & " !"
End Sub
Sub macro_test()
If Range("A1") = "" Then
warning "empty cell" '“空单元格”
ElseIf Not IsNumeric(Range("A1")) Then
warning "non-numerical value" '“非数值”
End If
End Sub
vbYesNo 指定对话框按钮为“Yes”和“No”,vbYes 代表“Yes”按钮:
If MsgBox("Text", vbYesNo, "Title") = vbYes Then '如果按下Yesbl_按钮...
| 持续的 | 数值 | 描述 |
|---|---|---|
| vbOKOnly | 0 | ![]() |
| vbOKCancel | 1 | ![]() ![]() |
| vbAbortRetryIgnore | 2 | ![]() ![]() ![]() |
| vbYesNoCancel | 3 | ![]() ![]() ![]() |
| vbYesNo | 4 | ![]() ![]() |
| vbRetryCancel | 5 | ![]() ![]() |
| vbCritical | 16 | ![]() |
| vbQuestion | 32 | ![]() |
| vbExclamation | 48 | ![]() |
| vbInformation | 64 | ![]() |
下面是一个 MsgBox 示例,每次循环中都会继续显示,直到用户按下 Yes:
Sub humor()
Do
If MsgBox("Do you like the Moonexcel site ?", vbYesNo, "Survey") = vbYes Then
Exit Do '=> 响应 Yes = 是的,我们退出循环
End If
Loop While 1 = 1 '=> 无限循环
MsgBox ";-)"
End Sub
要显示新功能区,您可以使用带有参数 10 的 Chr 函数,该函数负责移动功能区,例如:
MsgBox "Example 1" & Chr(10) & "Example 2" & Chr(10) & Chr(10) & "Example 3"
我们得到以下结果:
输入框提示用户在对话框中输入值,例如:
Sub example()
Dim result As String
result = InputBox("Text ?", "Title") '该变量被分配在输入框中输入的值
If result <> "" Then '如果该值不是“”,则将显示结果
MsgBox result
End If
End Sub
我们得到以下结果:
第三个参数可用于设置默认值:
InputBox("Text ?", "Title", "Default value")
结果如下: