在Excel中显示一段时间的弹出窗口

时间:2016-11-16 11:29:46

标签: excel-vba popup msgbox vba excel

我正在尝试在Excel VBA中生成一个弹出窗口,该弹出窗口在给定WaitTime秒后自动关闭。我查询了帖子“VBA Excel macro message box auto close”以及thisthis链接。我试图从引用的StackExchange线程中应用该方法;我的代码如下:

Sub TestSubroutine()

Dim TemporalBox As Integer
Dim WaitTime As Integer
Dim WScriptShell As Object

Set WScriptShell = CreateObject("WScript.Shell")

WaitTime = 1
TemporalBox = WScriptShell.Popup("The message box will close in 1 second.", _
WaitTime, "File processed")

End Sub

然而,它似乎不起作用,弹出窗口显示但在1秒后它永远不会关闭。

有人发现我做错了吗?

编辑#1

根据@Skip Intro评论,我更新了代码:

Sub TestSubroutine()

Dim WaitTime As Integer

WaitTime = 1
CreateObject("WScript.Shell").Popup "The message box will close in 1 second.", _
WaitTime, "File processed"

End Sub

然而,这并没有解决原始问题,弹出窗口在1秒后没有关闭。

编辑#2

这是@Glitch_Doctor建议的代码,但它仍然不起作用:

Sub TestSubroutine()

Dim TemporalBox As Integer
Dim WaitTime As Integer
Dim WScriptShell As Object
Dim test

Set WScriptShell = CreateObject("WScript.Shell")

WaitTime = 1
Select Case TemporalBox = WScriptShell.Popup("The message box will close in 1 second.", _
WaitTime, "File processed")
    Case 1, -1
End Select

End Sub

4 个答案:

答案 0 :(得分:2)

另一种方法(如果你根本不工作的话)。

创建名为 frm_Popup 的新用户表单,并添加名为 lbl_Message 的标签。将以下void添加到userform代码:

Public Sub StartProcess(iTime As Integer)
    Me.lbl_Message.Caption = "The message box will close in " & iTime & " second(s)."
End Sub

然后在你的模块中:

Sub ShowMessage()
    Dim iTimeToWait As Integer
        iTimeToWait = 2

    With frm_Popup
        .Show False
        Call .StartProcess(iTimeToWait)
    End With

    Application.OnTime Now + TimeValue("00:00:" & iTimeToWait), "HidePopup"
End Sub

Private Sub HidePopup()
    Unload frm_Popup
End Sub

答案 1 :(得分:1)

我终于找到了一个非常简单的解决方案 - @Orphid的信用,请参阅以下thread中的答案。

我没有解决与原始代码相关的具体问题,但我设法创建了一个在指定时间段后关闭的PopUp。代码如下:

Sub subClosingPopUp(PauseTime As Integer, Message As String, Title As String)

Dim WScriptShell As Object
Dim ConfigString As String

Set WScriptShell = CreateObject("WScript.Shell")
ConfigString = "mshta.exe vbscript:close(CreateObject(""WScript.Shell"")." & _
               "Popup(""" & Message & """," & PauseTime & ",""" & Title & """))"

WScriptShell.Run ConfigString

End Sub

这很好用。

答案 2 :(得分:0)

您只是错过了Select Case

WaitTime = 1
Select Case TemporalBox = WScriptShell.Popup("The message box will close in 1 second.", _
WaitTime, "File processed")
    Case 1, -1
End Select

我测试过它有效......

答案 3 :(得分:-1)

以下代码对我有用:

Sub TimeBasedPopUp()

Dim WaitTime As Integer

WaitTime = 1
Select Case CreateObject("WScript.Shell").Popup("The message box will close in 1 second.",_
WaitTime, "MS Excel")
Case 1, -1

结束选择

结束子