Closing a form on initialize throws error - excel

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?

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

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

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.

Sub RunForm()
On Error GoTo error
UserForm1.Show
error:
End Sub

Related

VBA userform listbox right click menu?

I'm creating a userform in excel. I've created the form, I've populated it with data using a Listbox that reads from a range in excel.
Now I'm trying to add the ability to right click on a row in the Listbox and then perform an action on that line of data form there. Is this possible? I had assumed it was so I was planning on:
Creating a custom popup menu
Working on setting up some sort of event in the userform on right click
Everything else.
I'm stuck on step 1 above. I started by trying to create a custom right-click menu by using the code from Microsoft's website on "showpopup".
https://learn.microsoft.com/en-us/office/vba/api/office.commandbar.showpopup
Private Sub UserForm_Initialize()
Set myBar = CommandBars _
.Add(Name:="Custom", Position:=msoBarPopup, Temporary:=False)
With myBar
.Controls.Add Type:=msoControlButton, ID:=3
.Controls.Add Type:=msoControlComboBox
End With
myBar.ShowPopup
End Sub
This is my code currently, I created a new userform and just pasted the code verbatim from MS's website. When I run the code I get this error:
"Run-time error: '5': Invalid procedure call or argument"
This is the line that's causing the error:
Set myBar = CommandBars _
.Add(Name:="Custom", Position:=msoBarPopup, Temporary:=False)
I'm at a loss on what the error is. Am I on the wrong track here? Am I just doing this whole thing completely wrong?
The reason for the error is that the CommandBar already exists ... before the line that is erroring, add:
On Error Resume Next
CommandBars.Item("Custom").Delete
On Error GoTo 0
... you should also really run the same lines to delete the CommandBar when your UserForm is no longer in use, maybe in the Terminate event
... also your code, as it stands, shows the CommandBar immediately, you likely want to move the myBar.ShowPopup line elsewhere (eg to the appropriate event handler for the ListBox)

Attempting to redraw Treeview, but Userform after Unload statement

I have a Userform setup to collect user input on creating a directory with subfolders and files. The input is through the use of a Treeview, and the file structure is predetermined with default selections Checked on or off. The user can toggle the creation of these subfolders and files to suit their needs. I added the options to "Select All" and "Clear All", something easy to do with Treeview Nodes.I also wanted to give users the option to restore the default selections. To that end, I added a "Default Selection" CommandButton that unloads the Userform and then load a fresh instance.
During testing, I noticed a strange bug in my code. There is a Msgbox that pops up to tell me that the script has worked without any errors. However, for every instance the user clicks "Default Selection", the Msgbox pops up that many more times. For example, if the user clicked "Default Selection" 3 times (I don't know why they would, other than being click happy and accident prone...), the Msgbox pops up 4 times; once for the successful test, and 3 more times for each time the button was clicked.
This is the Userform code stripped down to just a single CommandButton cmdDefaultSelect:
Option Explicit
Private Sub cmdDefaultSelect_Click()
'Reset default node checked values by reloading form
Unload Me
Call TestUnloadUserform
End Sub
...and here is the test module with the same symptoms:
Option Explicit
Public Sub TestUnloadUserform()
Dim frM As frmTest
Set frM = SetupTestFrm()
frM.Show vbModal
'Unload userform if it's already loaded
'This sub first loads the form
'Once the form is unloaded by cmdDefaultSelect_Click,
'the script continues to run from here, immediately
'after frM.Show
'If it's not unloaded here, then there is usually an error
If Not frM Is Nothing Then
Set frM = Nothing
End If
MsgBox _
Prompt:="Test complete.", _
Buttons:=vbOKOnly + vbInformation, _
Title:="Great Job"
End Sub
Public Function SetupTestFrm() As frmTest
Set SetupTestFrm = New frmTest
'In actual form, this is where the Treeview and Node properties are set
End Function
For a first draft, it works. The extra code is not included in this example, but the subfolder and files are created without an error. This was also the simplest solution I could come up with to essentially redraw the Treeview. However, I know I'm not loading/unloading my Userform correctly, and I'm probably going to run into trouble later on as I add more features. I don't want the script to end everytime the Userform is unloaded, but I'm unsure on how to structure the code between the Userform and standard modules.

VBA Excel - Unloading form leads to entire application termination

I am calling a userform A from within another userform B. The problem arises when I try to close the userform B. I don't want to use Hide method, because there are some default values assigned to form properties in the form's Load method - and I would like these values to be reassigned every time the user closes up and opens the form during one session.
So it appears that I should use Unload Me, but the latter stops my entire application as if I used End command.
So the question is, why Unload Me shuts down the entire application, rather than a single form.
Edit: Using Unload showUserFormB instead of Unload Me does not help
Private Sub methodOfUserFormA()
Call FormB.showUserFormB(some_params)
Unload SqlUpload__handlePhantomRows
Msgbox "Why Unload method shuts down entire app?"
End Sub

Stop tabbing out of textbox

I have an userform in Excel. I have put a check on one of the textbox, which will throw an error when any invalid data is input. The check has been put in the in the After Update event. However, I do not want to be tabbed out of the textbox after the error message is throw. How may I achieve that? Please find below code:
Private Sub txt_Textboc_After Update()
If CInt(txt_Textboc.Value) > 50 Then
Msgbox "Invalid Input"
End If
What additional code should I put in to avoid tabbing out if the code executes this If block?
You will need to bring focus back to the TextBox if there is an error.
TextBox1.SetFocus
That should make you 'untabbed'

Method 'Close' of object _Workbook failed when using UserForm in Excel 2011

I have already looked at these two posts:
Closing a Userform with Unload Me doesn't work
Error when closing an opened workbook in VBA Userform
They both suggest that when you want to close a file from Form code, you need to Unload the Form first (using Unload Me). However, if I Unload, I have a global array that's getting dereferenced.
Take a look at my code below though (which crashes on assigning global_int(0,0) to test). I can't Unload the Form unless I remove the array. Is this really the only solution to this problem?
Create a fresh excel file. In it, create a Userform. On that, create a Command Button with the following Click event code and global declaration:
Private global_int(2, 10) As Integer
Private Sub CommandButton1_Click()
global_int(0, 0) = 23
Dim filename As String
Dim opened_workbook As Workbook
filename = Application.GetOpenFilename() ' User selects valid Excel file
Set opened_workbook = Application.Workbooks.Open(filename)
' File operations would occur here
Unload Me
opened_workbook.Close ' Exception thrown here
Dim test As Integer
test = global_int(0, 0)
MsgBox "If you got here, it worked!"
End Sub
I'm just adapting someone else's code to work on a Mac, so I'd like to avoid completely refactoring if possible.
Thanks.
based on what I can understand is you have a userForm and the code is inside there. You can't unload the user form from inside the userForm code and expect the rest of the code to work. One option would be to write the code in a separate module. Call the user form to run from there

Resources