Thursday, 26 October 2017

VBA - Windows Script Host Object Model - Timed Popups

So Windows Script Host Object Model has a timed popup message box which is great if it worked as described. The bug lies in the duration, from VBA one can call asking for a popup to be timed to one second but it hangs around much longer, say 5-8 seconds. The solution, as found on StackOverflow, is to shell a HTML Application (HTA) which runs the command.

It is a shame this does not work flawlessly because otherwise we could advocate it to those Excel programmers who like to throw message boxes. Be aware that if you run an Excel VBA application unattended, say on a server, then there is nobody there to dismiss any message boxes and so processes can get stuck. Timed popus allow an application to proceed even when unattended.


Option Explicit

Sub TestTimedPopup()


    Dim oShell As IWshRuntimeLibrary.WshShell
    Set oShell = New IWshRuntimeLibrary.WshShell
    
    '* this hangs around for a period longer than 1 second, up to 8 seconds!!!
    oShell.Popup "Hello world, gonna hang around for longer than 1 second", 1, "mytitle", 0
    


End Sub

Sub TestTimedPopup2()

    '* with thanks to stackoverflow.com
    'https://stackoverflow.com/questions/31141775/infobox-popup-refuses-to-close-on-timer-expiration#answer-31143673

    Dim oShell As IWshRuntimeLibrary.WshShell
    Set oShell = New IWshRuntimeLibrary.WshShell

    '* in case you are wondering c:\windows\SysWOW64\mshta.exe
    '* is the Microsoft HTML Application host, part of the Internet Explorer product suite
    '* it allows running vbscript and javascript outside a web browser's sandbox
    oShell.Run "mshta.exe vbscript:close(CreateObject(""WScript.shell"").Popup(""Hello world, gonna hang for exactly 1 second"",1,""mytitle""))"

    '* HTA Developers page is mothballed so you 'll need to use an Internet archive , try this
    '* https://web.archive.org/web/20070305033902/http://www.microsoft.com:80/technet/scriptcenter/topics/htas/tutorial1.mspx

End Sub


No comments:

Post a Comment