Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically execute some code after the UserForm is drawn

Tags:

excel

vba

I have created a UserForm where the user is required to fill-in three fields. The macro attempts to auto-detect these fields' values in the UserForm_Initialize() event, then displays the found values in the three fields, but the user can change them. The auto-detection takes a few seconds, though, and delays the appearance of the UserForm. I'd like the UserForm to appear with its fields blank before the auto-detection procedure, then have the auto-detection procedure fill the fields automatically. What would be the best way to do this? Making the UserForm non-modal makes the macro run without waiting for the user's input, which is problematic. I don't want to have an "auto-detect" button: this has to be done automatically.

like image 690
Cutter Avatar asked Apr 02 '12 12:04

Cutter


People also ask

What is .show in VBA?

The VBA Userform. Show method does exactly what one would expect: it displays the userform on the screen.

How do I trigger VBA code in Excel?

Insert VBA code to Excel Workbook Open your workbook in Excel. Press Alt + F11 to open Visual Basic Editor (VBE). Right-click on your workbook name in the "Project-VBAProject" pane (at the top left corner of the editor window) and select Insert -> Module from the context menu. Copy the VBA code (from a web-page etc.)

What is a macro triggered event?

A workbook event is defined as an action that triggers the execution of a specific macro in Excel. VBA automatically executes an event once a user specifies the code for an event that has already occurred. An example of a VBA worksheet event is Open, which is triggered as soon as a Workbook is activated.


1 Answers

Use the Activate() event instead of Initialize() :)

Private Sub UserForm_Activate()

End Sub

FOLLOWUP

Thanks! It works, but there seems to be a bug: the dialog is drawn all white until the macro completes. screenshot (the dialog should be gray)

No. It is not a bug :) Try This. Add Doevents as shown below.

Private Sub UserForm_Activate()
    UserForm1.ProgressBar1.Value = 0
    starttime = Timer
    While Timer - starttime < 1
        UserForm1.ProgressBar1.Value = (Timer - starttime) * 100
        DoEvents
    Wend
End Sub

HTH

Sid

like image 101
Siddharth Rout Avatar answered Nov 15 '22 09:11

Siddharth Rout