Implementing a Progress Bar in Word VBA

Article contributed by Ibby

When the code you've written takes a long time to run, you may find it useful to display a UserForm with a Progress Bar that shows the user the progress of the operation. The following illustrates an example of how to create such a UserForm.

1.

Create a new project (open a new document).

2.

Insert a UserForm (UserForm1) and a Module (Module1)

3.

On the UserForm, place a Frame and place a Label inside the Frame. Change the following properties of the Frame and Label:

Frame1

 

Width = 200

 

Left = 18

 

Height = 30

 

Caption – set to nothing

Label1

 

Width = 0

 

Left = 0

 

Height = 27

 

Top = 0

 

Caption – set to nothing

 

BackColor – choose blue

4.

In Module1, paste the following code:

Option Explicit

Public Sub TestProgress()

UserForm1.Show
MsgBox "Process Finished"

End Sub

5.

In the UserForm1 module, paste the following code:

Option Explicit

Private Sub UserForm_Activate()

Dim i As Long
Dim oPara As Paragraph

' Me.Repaint allows proper painting of the userform.
' Leave it out and see what happens !!

Me.Repaint

For i = 1 To 10000

    ' Create 10000 dummy paragraphs in ActiveDocument
    ActiveDocument.Paragraphs.Last.Range. _
            Text = "Test Paragraph " & i & vbCr

    ' Increase size of Label1 incrementally
    Label1.Width = i / 50

     ' Repaint allows Label1 to display as it is enlarging
    Frame1.Repaint

Next i

' Unload UserForm when process finished
Unload Me

End Sub

6.

Now Run the macro TestProgress to see how this works.

Note that if you run the macro from the VB Editor, the progress bar may still look a little strange, even using the Me.Repaint line; but it looks fine if you run the macro from Word – as a user would do – by clicking a toolbar button or a shortcut key, or by selecting Tools + Macro + Macros + Run.

It is much better to use Me.Repaint rather than the alternative of DoEvents, because the latter is very resource-hungry.