In a VBA project of mine I am/will be using a series of reasonably complex userforms, many of which are visually identical but have different subroutines attached to the buttons. As a result I'm not overly keen on the idea of duplicating them multiple times in order to get different functionality out of the same layout. Is it possible to have a userform detect which subroutine called it and use this in flow control? I would like to be able to do something like this:
Private Sub UserForm_Initialize()
If [the sub that called the userform is called "foo"] then
Call fooSub
else
Call barSub
End If
End Sub
My backup plan is to have the calling subroutine set a global variable flag and have the userform check that, but that seems like a rather crude and clumsy solution.
Thanks everyone,
Louis
You can use the tag property of the form. Load the form, set the property, then show the form:
Sub PassCallerToForm()
Load UserForm1
UserForm1.Tag = "foo"
UserForm1.Show
End Sub
Now that the property is set, you can determine what to do in the form:
Private Sub UserForm_Activate()
If Me.Tag = "foo" Then
Call fooSub
Else
Call barSub
End If
End Sub
You can also use public variables:
' in userform
Public Caller As String
Private Sub UserForm_Click()
MsgBox Caller
Caller = Now()
Me.Hide
End Sub
' in caller
Sub callUF()
Dim frm As New UserForm1
frm.Caller = "Test Caller"
frm.Show
MsgBox frm.Caller ' valid after Me.Hide
Set frm = Nothing
End Sub
Personally, I would not have one userform doing two disparate activities. The code would get hard to read pretty quickly, I think. Copying the layout of a userform is pretty trivial.
To copy a userform: Open a blank workbook. In the Project Explorer, drag the userform to the new workbook. Rename the userform in the new workbook. Now drag it back to the original workbook. Change the code in the userform copy.
If you absolutely don't want separate userforms, I recommend setting up a property of the userform. Userforms are just classes except they have a user interface component. In the userform module
Private mbIsFoo As Boolean
Public Property Let IsFoo(ByVal bIsFoo As Boolean): mbIsFoo = bIsFoo: End Property
Public Property Get IsFoo() As Boolean: IsFoo = mbIsFoo: End Property
Public Sub Initialize()
If Me.IsFoo Then
FooSub
Else
BarSub
End If
End Sub
I always write my own Initialize procedure. In a standard module:
Sub OpenForm()
Dim ufFooBar As UFooBar
Set ufFooBar = New UFooBar
ufFooBar.IsFoo = True
ufFooBar.Initialize
ufFooBar.Show
End Sub
Related
Is it possible to get the same effect using ThisWorkbook.Application.Visible = False but only for one Workbook. I mean, I'd like to limiting user interaction only to UserForm, but I need have an access to anothers workbooks. At the moment this function cause hide workbook, but after open some another excel file - all object from userform are not available.
Private Sub Workbook_Open()
ThisWorkbook.Application.Visible = False
Starter.Show modeless
End Sub
Thanks for your support.
Please, create a form, let us say "Starter", having (at least) a button ("btExit"), copy the next code in its code module and show it. If the form in discussion already has some code in Initialize and Terminate events, please add the next code lines, too:
Option Explicit
Private Sub btExit_Click()
Unload Me
End Sub
Private Sub UserForm_Initialize()
ThisWorkbook.Windows(1).Visible = False
End Sub
Private Sub UserForm_Terminate()
ThisWorkbook.Windows(1).Visible = True
End Sub
So, you can simple use workbook Open event in this way:
Private Sub Workbook_Open()
Starter.Show vbModeless
End Sub
I might miss just a stupid small detail but I don't get a hang on it.
I've created a userform with a listbox where I want the user to select one item. This is working so far as my variable "termin" has the right value before I close the user form
Private Sub OKButton_click()
termin = Eventlist.List(Eventlist.ListIndex)
MsgBox termin 'Just for testing purposes. It gives me the selected item
Unload Eventabfrage
End Sub
And this is a part of what I have in 'ThisOutlookSession':
Option Explicit
Dim termin As String
Public Sub MailMerge()
Eventabfrage.Show
MsgBox termin 'and there it is empty but shouldn't be empty
enter code here
End Sub
What do I have to do to hand over the value to my MailMerge Sub?
It is a macro in Outlook so storing it in any Excel cell is not an option.
Other than using Public variable (which I would only as the last chance since it's prone to many drawbacks), you can use UserForm class Tag property to pass info in and out an instance of a Userform and a more safe Userform instantiating and terminating scheme, as follows:
in the calling module:
Public Sub MailMerge()
Dim termin As String ' declare 'termin' as a Sub scoped variable
With New Eventabfrage ' get a new instance of the wanted userform class and reference it
.Show
termin = .Tag ' retrieve referenced userform 'Tag' property and store it in 'termin' variable
'enter code here
End With ' <-- this will unload the userform instance
End Sub
in the Eventabfrage class module
Private Sub OKButton_Click()
With Me ' reference the Userform class current instance
.Tag = .Eventlist.List(.Eventlist.ListIndex)
.Hide ' hide the userform instead of unloading it, so as to have it "alive", along with its properties (and methods) in its calling sub
End With
End Sub
Appologies if this has been asked already, but I cannot seem to find an answer. I want to set a do something on a UserForm as it is loaded up based on the value passed to it from a property. What I have is a button on an Excel worksheet which loads the user form as follows:
Sub button()
Dim fm As New UserForm1
fm.ValueToPass = "Hello"
fm.Show
End Sub
Behind the form is the following code:
Private myString As String
Public Property Let ValueToPass(ByVal x As String)
myString = x
End Property
Private Sub UserForm_Initialize()
If myString = "Hello" Then
'Do something on my form
else
'Do something else on my form
end if
End Sub
The problem is that when the form is loaded up, the myString is empty. I believe that the reason is that the form is initialised before the property ValueToPass is set. What is the best solution to this?
You probably think that when you call:
fm.ValueToPass = "Hello"
in Private Sub UserForm_Initialize() it is possible that the myString value is passed before initializing the form. E.g., you are somehow expecting that myString can be something different than "" (thus you have the condition). This is not the case - first the _Initialize constructor is executed and then anything else is carried out:
With your code, you need somehow to tell the form, that it should update its label. Consider this inside the form:
Public Sub ShowForm()
Me.Label1 = myString
Me.Show
End Sub
Then in the module, call it like fm.ShowForm instead of fm.Show.
Actually, it is a good idea, if you work with userforms, following the Model-View-Controller pattern. For this you would need a separate class.
Userform closes after "End Sub" without ever calling "Unload Me"
Easiest way:
Sub button()
Dim fm As New UserForm1
fm.Label1.Caption = "Hello"
fm.Show
End Sub
you should be using the initialize event for this:
Sub OpenForm()
MyForm.show
end sub
Then in the initialize event of the userform, put this:
Me.LabelName.Caption = "Your label text"
(double-click the userform to view its code, then select from the top right drop-down "Initialize".)
There's a lot of information and a lot that you can do with userforms but I can't really find a standard way to use them. Let's say I have a userform with a standard dropdown list that asks someone to choose a fruit. In the userform code I will put the below code after adding a combo box called fruitcombo:
Private Sub UserForm_Initialize()
userform1.fruitcombo.AddItem "Peach"
userform1.fruitcombo.AddItem "Pear"
userform1.fruitcombo.AddItem "Grape"
End Sub
I will also add a commandbutton which will be labeled "Submit" and in that event:
Private Sub Submit_Click()
Me.Hide
End Sub
That's where it starts to get hazy. What's the best way to capture the answer that was selected? One way I can think would be to make a global variable called fruitanswer and then instead of the Me.Hide we can skip straight to Unload Me
Ex:
Private Sub Submit_Click()
fruitanswer = fruitcombo.value
Unload Me
End Sub
Or we can have fruitanswer as a private variable in the module where the userform is called and then unload it in there. There are also multiple ways to initialize the userform. I'm also wondering the best way to initialize it. The Show method will automatically initialize it, but the Hide method WON'T automatically de-initialize it. For that, the Unload statement is necessary. So does anyone initialize it before calling the Show method using the Load statement?
Ex:
Load userform1 'Any point to including this?
userform1.show
'user chooses a fruit and clicks submit button
'userform is hidden by commandbutton but not unloaded yet
fruitanswer = fruitcombo.value
Unload userform1
Out of these options, which is the best method? Is there anything to make it more efficient?
You can wrap the whole thing in a single function call:
strFruit = UserForm1.GetFruit()
Then, in your UserForm, have it do the work of displaying and unloading itself like so:
Private bOK As Boolean
Public Function GetFruit() As String
bOK = False
Me.Show vbModal
If bOK Then GetFruit = ComboBox1.Text
Unload Me
End Function
Private Sub cmdOK_Click()
bOK = True
Me.Hide
End Sub
Private Sub cmdCancel_Click()
Me.Hide
End Sub
This assumes you have buttons named cmdOK and cmdCancel and a combobox named ComboBox1.
Since Show() is being called modally, the code after it won't execute until the form is closed or hidden. When either button is clicked (or the form is closed by other means) then the code continues, the selected text is returned (if OK was clicked), and the form unloads itself.
The beauty of doing it this way is that your calling code doesn't need to worry about instantiating and destroying the form each time it's called. It's just a single statement to load the form and get the return value.
Of course, you'll need to add the code to populate the combobox with whatever items you wish to display.
I have a userform with a basic combobox and command button. When the user hits the command button, I want the UserForm to close, and the value of the combobox to be saved in a variable that can be accessed by a subroutine contained within "ThisWorkbook".
In the UserForm code:
Public employee_position As String
Public Sub CommandButton1_Click()
employee_position = Me.ComboBox1.Value
Unload Me
End Sub
In the "ThisWorkbook" Code
Private Sub GetUserFormValue()
Call Userform_Initialize
EmployeePosition.Show
MsgBox employee_position
End Sub
When "GetUserFormValue()" runs, the UserForm comes up, you can select a value in the combobox and press the command button, but when the MsgBox comes up, it displays "" (Nothing)
What am I doing wrong here?
When you Unload Me, I think you lose all information associated with the module (including the global variable). But if you use Me.Hide rather than Me.Unload, then you can access the value of the form after the routine returns. So try this:
-- userform code includes:
Public Sub CommandButton1_Click()
Me.Hide
End Sub
-- main module includes:
Private Sub GetUserFormValue()
Call Userform_Initialize
EmployeePosition.Show
MsgBox EmployeePosition.ComboBox1.Value
Unload EmployeePosition
End Sub
I think that should work.
I had the same problem, and this is how I resolved it:
If the main code is in a worksheet, and the variable is declared as public in that worksheet (e.g. in Microsoft Excel Objects -> Sheet1 (Sheet1)), the result from "Unload Me" cannot be passed from a UserForm to the worksheet code.
So to solve my problem, I inserted a new Module, and declared my public variable there. I didn't even have to move my code from the worksheet to the module... just the declaration of the public variable.
I hope this works for you too!
Andrew