Question

I'm trying to set up a userform that will appear, remain for 10 seconds, and then close automatically. I have done this before in Excel, using the OnTime method:

Sub Example()
     Application.OnTime EarliestTime:=Now + TimeValue("00:00:10"), _ 
     Procedure:="Hide_userform2"
     UserForm2.Show
End Sub

Sub Hide_userform2()
     UserForm2.Hide
End Sub

However, because Outlook doesn't recognise the OnTime method, I have been trying to use the Timer statement:

Sub example2()
Strt = Timer
Do While Timer < Strt + 10
    UserForm2.Show
Loop
UserForm2.Hide
End Sub

The problem with this is that when the user form opens, the macro (including the loop) pauses until the UserForm is manually closed...

Any help on a workaround for this would be much appreciated.

Cheers!

Was it helpful?

Solution

I ran some tests and the problem seems to be that once you show the User Form, it takes control and does not return it to example2().

What seems to work is if you put the following code in your form's Acitvate sub, it will hide correctly. This may not be exactly what you want, you may be using the form for other things and this process will mess it up, but it gets you in the right direction.

Private Sub UserForm_Activate()
    Strt = Timer
    Do While Timer < Strt + 10
        DoEvents 'please read linked documentation on this
    Loop
    UserForm2.Hide
End Sub

Using DoEvents will make sure the form shows correctly but may have some unwanted side effects. Make sure to read this Microsoft article and a blog post by Jeff Atwood is an interesting read though not necessarily about VBA.

OTHER TIPS

This page provides a custom timer add-in (.xla) that may work for you. It's the same idea as the code you have above (this would go in the form code-behind):

Dim WithEvents CountdownTimer As TMTimer.clsTimer

Private Sub startCounter()
    Set CountdownTimer = TMTimer.createTimer
    With CountdownTimer
        .CountdownDurationMilliSecs = 10 * 1000
        .TimerType = .TimerTypeCountdown
        .startTimer
    End With
End Sub

Private Sub CountdownTimer_CountdownComplete()
    Me.Hide
End Sub

Private Sub UserForm_Activate()
    startCounter
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top