VBA: 自动定时关闭消息框

2022-12-18 11:51:20 浏览数 (1)

文章背景: 在VBA中创建弹窗对话框,可以使用MsgBox函数;但是该函数得到的消息框,必须手动关闭它。下面介绍一个未公开的Windows API函数,可以使用该函数得到一个自动定时关闭的消息框。

代码语言:javascript复制
Option Explicit

#If VBA7 And Win64 Then
Private Declare PtrSafe Function MessageBoxTimeout Lib "user32" _
    Alias "MessageBoxTimeoutA" (ByVal hwnd As Long, _
                                ByVal lpText As String, _
                                ByVal lpCaption As String, _
                                ByVal wType As Long, _
                                ByVal wlange As Long, _
                                ByVal dwTimeout As Long) As Long
#Else
Private Declare Function MessageBoxTimeout Lib "user32" _
    Alias "MessageBoxTimeoutA" (ByVal hwnd As Long, _
                                ByVal lpText As String, _
                                ByVal lpCaption As String, _
                                ByVal wType As Long, _
                                ByVal wlange As Long, _
                                ByVal dwTimeout As Long) As Long
#End If

Sub Demo1()

    ' 只有“确定”按钮
    
    MessageBoxTimeout 0, "3 秒后自动关闭", "DEMO1", 0, 0, 3000
    
    ' MsgBox "VBA消息框", vbOKOnly, "DEMO1-VBA"
    ' vbOKOnly    0
    
End Sub

Sub Demo2()

    ' 共三个按钮,其中第二按钮为默认。
    
    MessageBoxTimeout 0, "3 秒后自动关闭", "DEMO2", 275, 0, 3000
    
    'MsgBox "VBA消息框", vbDefaultButton2   vbCritical   vbYesNoCancel, "DEMO2-VBA"
    'vbDefaultButton2    256
    'vbCritical          16
    'vbYesNoCancel       3

End Sub

(1)代码开头先声明API函数MessageBoxTimeout。针对64位office环境和32位office环境,分别编写相应的代码。

  • hwnd: 窗口句柄
  • lpText:消息框提示信息;对应Msgbox函数的Prompt
  • lpCaption: 消息框标题; 对应Msgbox函数的Title
  • wType: 消息框类型;对应Msgbox函数的Buttoms
  • wlange: 函数扩展,通常为0。
  • dwTimeout: 延迟关闭时间,单位:毫秒。 (2)视频演示

http://mpvideo.qpic.cn/0bc3pyacgaaasiaf3zpsanrfa7wden7aaiya.f10002.mp4?dis_k=a2e0a88ed2a2a8cfa3551eb8c7822282&dis_t=1671335454&play_scene=0&vid=wxv_2524419061737472001&format_id=10002&support_redirect=0&mmversion=false

参考资料:

[1] MsgBox function(https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/msgbox-function)

[2] VBA中实现自动关闭消息框(https://blog.csdn.net/taller_2000/article/details/113987559)

[3] 用vba做一个自动定时关闭的msgbox对话框(http://www.exceloffice.net/archives/6105)

0 人点赞