4

I'm trying to make a standardized process for updating a particular worksheet. I want no user control except for the functions I give them. To do that I have locked sheets and then forms that load with certain macros. One form is designed to remove data from the sheet. It works fine as written and tested, but I've tried to update it so that if you open it without any relevant data to remove, it spits out a dialogue box and then uses Unload Me to close the form. This closes the form but then excel throws an error:

Run-time error '91': Object variable or With block variable not set

The form is loaded from a module that only has the one line:

MyForm.Show

This is where excel is throwing the error from. On initialization of the form, a combobox is filled with values based on the data in the sheet. If the combobox is empty after loading, the form is supposed to throw the dialogue box and then close.

If ComboBox.ListCount = 0 Then
    MsgBox "No Data"
    Unload Me
End If

How can I perform the check on load without having the error thrown from the Module?

1
  • Have you simply tried Me.Hide ? I think the Unload method fails because of some references that forbid you to remove it from the stack memory.
    – Matteo NNZ
    Dec 2, 2014 at 22:33

4 Answers 4

6

This doesn't actually answer your question. But what I suggest is do the checking in your module code before you actually load the form. Something like:

Sub LoadForm()
    If Sheets("Sheet1").Range("A1") = "" Then '<~~ your condition here
        MsgBox "No Data"
    Else
        MyForm.Show
    End If
End Sub
0
4

The problem happens when you try and unload the userform from within it's initialize event. Because the object hasn't finished initialization yet, it cant be unloaded. The best ways to get around this are either to check conditions before you try to initialize the form, or put your checks and subsequent unload statements into the activate event of the userform. Activate is called whenever the form goes from being hidden to visible, which happens after the form has been completely initialized.

3

Another way would be to place the Unload Me in the Activate event:

Private Sub UserForm_Activate()
    ...
    If ComboBox.ListCount = 0 Then
       MsgBox "No Data"
       Unload Me
    End If
End Sub
1
Sub RunForm()
On Error GoTo error
UserForm1.Show
error:
End Sub
1
  • Nice, thanks. For additional info: Launch the form with the suggested code, but still have the unload me in the failed initialization method
    – BmyGuest
    Aug 5, 2020 at 17:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.