Search code examples
excelvbaloadinguserformprogress

Why are loading bar in VBA created by using UserForms to call the main subroutine instead of the other way round?


I've read through quite a few tutorials on creating a loading bar or progress bar using UserForms in VBA but all of them guide me in the following steps:

  1. Create a button to call the UserForm
  2. UserForm calls subroutine
  3. Subroutine updates the bar
  4. Unload bar within subroutine

Why can't I do the following instead:

  1. Create a button to call the subroutine
  2. Subroutine calls UserForm
  3. Subroutine updates the bar
  4. Unload bar within subroutine

Thank you for your time!


Solution

  • There is nothing to stop you doing it that way. The code below shows a rough mock-up of the VBA required.

    This approach makes it easier to reuse your progress form elsewhere in this, and other, projects. Just make sure the progress logic, within the subroutine, is separated from the display logic, within the form.

    ' Event fired by a button on the Excel grid.
    Sub Example_OnClick()
    
        Dim myForm As UserForm1     ' Replace with your form here.
    
    
        ' Display the form.
        ' Ensure it is not modal, as this would prevent subsequent lines
        ' from executing while the form is open.
        myForm.Show False
    
        Do Until myForm.Progress = 100
    
            ' ToDo: Add processing logic here.
    
            ' Update the progress bar.
            myForm.IncrementPrgress 1
        Loop
    
        ' Remove the from
        Unload myForm
    End Sub