Here is a solution that supports carriage returns that use an API call instead of WScript.Shell and works in Excel VBA. It supports standard enumerated parameters like vbQuestion + vbYesNo
and can return the user response. 32000
is returned if the timeout occurs.
This also has the advantage of showing the popup on the same monitor as the app instead of the main display.
' This part needs to be at the top of a VBA module
#If Win64 Then
Private Declare PtrSafe Function MsgBoxTimeout _
Lib "user32" _
Alias "MessageBoxTimeoutA" ( _
ByVal hwnd As LongPtr, _
ByVal lpText As String, _
ByVal lpCaption As String, _
ByVal wType As VbMsgBoxStyle, _
ByVal wlange As Long, _
ByVal dwTimeout As Long) _
As Long
#Else
Private Declare Function MsgBoxTimeout _
Lib "user32" _
Alias "MessageBoxTimeoutA" ( _
ByVal hwnd As Long, _
ByVal lpText As String, _
ByVal lpCaption As String, _
ByVal wType As VbMsgBoxStyle, _
ByVal wlange As Long, _
ByVal dwTimeout As Long) _
As Long
#End If
Sub TestMsgbox()
Dim ReturnValue
ReturnValue = MsgBoxTimeout(0, "Do you like this message?" & vbCrLf & "This message box will be closed after 4 seconds." & vbCrLf & vbCrLf & "(See Immediate window for return value)", "Return Choice", vbQuestion + vbYesNoCancel, 0, 4000)
Select Case ReturnValue
Case vbYes
Debug.Print "You picked Yes."
Case vbNo
Debug.Print "You picked No."
Case vbCancel
Debug.Print "You picked Cancel."
Case 32000
Debug.Print "Timeout before user made selection."
End Select
End Sub
More info:
https://www.extendoffice.com/documents/excel/3836-excel-message-box-timer-timeout.html
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…