Return a value from a userform - excel

I am trying to return a value from a userform to another macro.
Here is an example of a piece of code that I want to return the value intMonth:
sub comparison()
UserForm1.Show
end sub
then I have the userform code:
Private Sub initialize()
OptionButton1 = False
End Sub
Private Sub OptionButton1_Click()
intMonth = 1
Me.Hide
End Sub
How do I get the intMonth value of 1 back to my original comparison() function?

This is a minimal example, but should help.
In the UserForm:
Option Explicit
Option Base 0
Public intMonth As Long ' <-- the variable that will hold your output
Private Sub initialize()
OptionButton1 = False
intMonth = 0
End Sub
Private Sub CommandButton1_Click() ' OK button
Me.Hide
End Sub
Private Sub OptionButton1_Click()
intMonth = 1 '<-- set the value corresponding to the selected radio button
End Sub
Private Sub OptionButton2_Click()
intMonth = 2
End Sub
In a module or ThisWorkbook:
Option Explicit
Option Base 0
Sub comparison()
UserForm1.Show
MsgBox CStr(UserForm1.intMonth) ' <-- retrieve the value
End Sub

Another useful way to achieve what you need is to wrap the code in a public function in the userform.
In the UserForm:
Option Explicit
Option Base 0
Private intMonth As Long
Public Function Choose_Option()
OptionButton1 = False
intMonth = 0
Me.show()
Choose_Option = intMonth
End sub
Private Sub CommandButton1_Click() ' OK button
Me.Hide
End Sub
Private Sub OptionButton1_Click()
intMonth = 1
End Sub
Private Sub OptionButton2_Click()
intMonth = 2
End Sub
Then in module, it is simple as this:
Option Explicit
Option Base 0
Sub comparison()
MsgBox Userform1.Choose_Option()
End Sub
This way, the function is in charge of showing the userform, prompting the user and returning the value.
If you debug this function, you will see that after Me.Show() is called, the function halts and continue only when the userform is hidden, which is done in the OK button.

Related

Continue procedure if CommandButton is clicked

So far I have used the below VBA in order to continue with a procedure if the user clicked ok in the MsgBox:
Sub Button_Message_Box()
Answer = MsgBox("Do you want to continue the procedure?", vbOK)
If Answer = vbOK Then
Sheet1.Range("A1").Value = 1
Else
End If
End Sub
Now I want to achieve the exact same result using CommandButton1 in UserForm1.
Therefore I tried to go with this:
(1) VBA in UserForm1:
Private Sub CommandButton1_Click()
Unload Me
End Sub
(2) VBA in Modul1:
Sub Button_Procedure()
Call UserForm1.Show(vbModeless)
If CommandButton1 = True Then
Sheet1.Range("A1").Value = 1
Else
End If
End Sub
The VBA goes through but it does not enter the value 1 into Cell A1.
What do I need to modify to achieve the desired result?
I strongly suggest to follow the steps in this article: Rubberduck: UserForm1.Show
Nevertheless, a simple and dirty implementation could be as follows:
The form's code behind:
Add an event to raise when the OK-Cancel button has been pressed passing a boolean value indicating either to proceed or not:
Public Event OnClose(ByVal bool As Boolean)
Private Sub CmdOK_Click()
RaiseEvent OnClose(True)
End Sub
Private Sub CmdCancel_Click()
RaiseEvent OnClose(False)
End Sub
A simple wrapper class:
Here, we just instantiate the form and listen to the OnClose() event.
Option Explicit
Private WithEvents objForm As UserForm1
Private m_flag As Boolean
Public Function Show() As Boolean
Set objForm = New UserForm1
objForm.Show ' No vbModeless here, we want to halt code execution
Show = m_flag
End Function
Private Sub CloseForm()
Unload objForm
Set objForm = Nothing
End Sub
Private Sub objForm_OnClose(ByVal bool As Boolean)
m_flag = bool
CloseForm
End Sub
Calling the wrapper class:
Sub Something()
Dim bool As Boolean
With New FormWrapper
bool = .Show
End With
MsgBox "Should I proceed? " & bool
End Sub
With reference to this question I used a Boolean variable:
(1) Code in UserForm1:
Private continue_procedure As Boolean
Private Sub CommandButton1_Click()
continue_procedure = True
Unload Me
End Sub
Function check_procedure() As Boolean
UserForm1.Show
check_procedure = continue_procedure
End Function
(2) Code in Modul1:
Sub Button_Procedure()
If UserForm1.check_procedure() = True Then
Sheet1.Range("A1").Value = 1
Else
End If
End Sub

Hows to Add UserForm TextBox Value to Cell using MVP Method

I am trying to add a TextBox string value to cell A1. I am barely learning the basics of writing code using an MVP (Modal, View, Presenter), after reading this article from Mathieu Guindon. I am getting a Compile Error: Variable not defined Error is found on Sheet1.Range("A1") = clientName Why?
Here is my code:
Userform Name: "UserForm1"
(code behind UserForm1)
Option Explicit
Public Event OnRunReport()
Public Event OnExit()
Public Property Get clientName() As String
clientName = clientNameBox.Text
End Property
Public Property Let clientName(ByVal value As String)
clientNameBox.Text = value
End Property
Private Sub clientNameBox_Change()
clientName = clientNameBox.Text
End Sub
Private Sub exitButton_Click()
RaiseEvent OnExit
End Sub
Private Sub submit_Click()
RaiseEvent OnRunReport
End Sub
Private Sub UserForm_Initialize()
RaiseEvent OnRunReport
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
Cancel = True
Hide
End If
End Sub
Module1
Option Explicit
Private objClientForm As UserForm1
Public Sub AddClientsToSheet()
Sheet1.Range("A1") = clientName '******error line *******
End Sub
Public Sub showMainForm()
If (objPresenter Is Nothing) Then
Set objPresenter = New AddClientsToSheet
End If
objPresenter.show
End Sub
ClassModule Name: AddClientsToSheet
Option Explicit
Private WithEvents objClientForm As UserForm1
Public Sub Class_Initialize()
Set objClientForm = New UserForm1
End Sub
Private Sub Class_Terminate()
Set objClientForm = Nothing
End Sub
Public Sub show()
If Not objClientForm.Visible Then
objClientForm.show
End If
With objClientForm
.Top = CLng((Application.Height / 2 + Application.Top) - .Height / 2)
.Left = CLng((Application.Width / 2 + Application.Left) - .Width / 2)
End With
End Sub
Private Sub Hide()
If objClientForm.Visible Then objClientForm.Hide
End Sub
Private Sub objClientForm_OnExit()
Hide
End Sub
Private Sub objClientForm_OnRunReport()
AddClientsToSheet
End Sub

Run this Worksheet_Calculate when opening workbook without running my Macro

Right now my process is working correctly, with the help of this community, however, I need this Worksheet_Calculate to NOT execute the Macro (MacroRuns for example) when the workbook opens, but I still need it to function the same way it is currently, after the workbook is opened.
Thank you so much for your help in advance!
The Code I Am Using:
in ThisWorkbook
Option Explicit
Private Sub Workbook_Open()
TargetStart
End Sub
in the target sheet's code window
Option Explicit
Private Sub Worksheet_Calculate()
Application.EnableEvents = False
TargetCalc Me
Application.EnableEvents = True
End Sub
in Module 1
Option Explicit
Public TargetValue As Variant
Private Const cTarget As String = "C3"
Sub TargetCalc(ws as Worksheet)
If ws.Range(cTarget) <> TargetValue Then
'this is where I would like the code to say something like, "if workbook just opened, exit -- otherwise continue. If this is even possible.
Call MacroRuns
TargetValue = ws.Range(cTarget).Value
End If
End Sub
Sub TargetStart()
TargetValue = Sheet1.Range(cTarget).Value
End Sub
Sub MacroRuns()
Call UpdateMsgBox
End Sub
I think that this can solve your problem:
In ThisWorkbook:
Private Sub Workbook_Open()
Worksheets("NameHere").Range("A1") = True
End Sub
In the target sheet's code window:
Private Sub Worksheet_Calculate()
If Worksheets("NameHere").Range("A1") Then MacroRuns
Worksheets("NameHere").Range("A1") = False
End Sub
Please try this arrangement.
Public StartUp As Boolean
Private Sub Workbook_Open()
StartUp = True
TargetStart
End Sub
Sub TargetCalc(ws As Worksheet)
If ws.Range(cTarget) <> TargetValue Then
If Not StartUp Then MacroRuns
StartUp = False
TargetValue = ws.Range(cTarget).Value
End If
End Sub
or, perhaps you prefer it to be like this.
Sub TargetCalc(ws As Worksheet)
If ws.Range(cTarget) <> TargetValue Then
If Not StartUp Then
MacroRuns
TargetValue = ws.Range(cTarget).Value
End If
StartUp = False
End If
End Sub

VBA Userform ComboBox instantiation

I have a Problem with a Userform which I called "ComboTest2". It only consists of two Comboboxes. If I instantiate the USerform as an object then the following Code doesn't work in the sense that the second combobox of the Userform doesn't contain the desired data.
Sub FillCombo(ByVal row As Long)
Dim rgCities As Range
Set rgCities = Worksheets("Tabelle2").Range("B2:D2").Offset(row)
ComboTest2.ComboBox2.Clear
ComboTest2.ComboBox2.List = WorksheetFunction.Transpose(rgCities)
ComboTest2.ComboBox2.ListIndex = 0
End Sub
Sub FillMain()
Dim ComboForm2 As ComboTest2
Set ComboForm2 = New ComboTest2
ComboForm2.Show
End Sub
UserForm-Code:
Private Sub CommandButton1_Click()
Me.Hide
End Sub
Private Sub CommandButton2_Click()
Me.Hide
End Sub
Private Sub ComboBox1_Change()
FillCombo ComboBox1.ListIndex
End Sub
Private Sub UserForm_Initialize()
ComboBox1.List = Worksheets("Tabelle2").Range("A2:A5").Value
ComboBox1.ListIndex = 0
FillCombo ComboBox1.ListIndex
End Sub
But if I use the "default instantiation" by VBA which means that I change the FillMain Sub to:
Sub FillMain2()
Dim ComboForm2 As ComboTest2
Set ComboForm2 = New ComboTest2
'ComboForm2.Show
ComboTest2.Show
End Sub
Then everything is fine. Why is that so?
Best regards
It's because FillCombo is referring to the userform by name, and therefore to the default instance (you're actually creating a new instance of the form). If that code is not in the userform, and I'm not sure why you would have it outside the form, you should pass the combobox as an argument to it.

How to pass value of ComboBox in userform to macro

I want to pass a value selected by user to be displayed in MsgBox. I write the following code but its display nothing.
Public Sub CommandButton1_Click()
SelectedCity = Me.ComboBox1.Value
DistSystem
End Sub
Sub DistSystem()
MsgBox (SelctedCity)
End Sub
Second procedure cannot read variable because of wrong scope.
You have to declare SelectedCity variable as global:
Global SelectedCity
Public Sub CommandButton1_Click()
SelectedCity = Me.ComboBox1.Value
DistSystem
End Sub
Sub DistSystem()
MsgBox (SelctedCity)
End Sub
There are times when you can't pass it in an argument, but you can pass it here.
Option Explicit 'forces to declare all variables
Public Sub CommandButton1_Click()
call DistSystem (Me.ComboBox1.Value)
'same as ( without call, and () ) :
' DistSystem Me.ComboBox1.Value
End Sub
Sub DistSystem(byval selectedCity$) 'same as: byval SelectedCity as string
MsgBox SelectedCity
End Sub
This works even if DistSystem is in a different module.
Declare Selectedcity as a public OUTSIDE of the Sub
Public SelectedCity as String
Public Sub CommandButton1_Click()
SelectedCity = Me.ComboBox1.Value
Call DistSystem
End Sub
Sub DistSystem()
MsgBox (SelectedCity)
End Sub
Obviously place DistSystem in a module!

Resources