Hows to Add UserForm TextBox Value to Cell using MVP Method - excel

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

Related

How to initialize a combo box in a form?

My understanding is that initialization code runs when I invoke "New UserForm2".
Below is the code that invokes a New userform and the code associated with the userform.
I stepped through with the debugger and watched it execute the initialization code, but it has no affect on the form. The combo box is still blank.
If TabID = "5 Client List" Then
With New UserForm2
.Show
If Not .IsCancelled Then
If InStr(TarSheet, "5.1") Then
Call General_Transfer(TabID, TarSheet, 28, "Yes")
End If
TarSheet = ""
End If
End With
Exit Sub
End If
' UserForm2 Code
Option Explicit
'#Folder("UI")
Private cancelled As Boolean
Public Property Get IsCancelled() As Boolean
IsCancelled = cancelled
End Property
Private Sub CommandButton1_Click()
TarSheet = Me.ComboBox1.Value
Hide
End Sub
Private Sub CommandButton2_Click()
TarSheet = ""
OnCancel
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
Cancel = True
OnCancel
End If
End Sub
Private Sub OnCancel()
cancelled = True
Hide
End Sub
Private Sub UserForm_Initialize()
UserForm2.ComboBox1.AddItem "5.1 Client List LTS"
End Sub

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

Return a value from a userform

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.

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!

Right-click withevents works on source .xlsm but not on .xlam addin

I've made a couple of macros that run through right click menu button based on the cell value. Typically, if I right click on cell with value 'XYZ', the menu button shows as 'Run macro for XYZ' and then does a bunch of operations: show a couple of user forms, run an SQL query, show and format result data.
On the original .xlsm file, on 'Thisworkbook' I have the following code:
Public WithEvents mxlApp As Application
Public WithEvents mxlSh As Worksheet
Private Sub mxlApp_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As
Boolean)
... (do stuff here) ...
End Sub
...
Private Sub Workbook_Open()
Call AutoExec
End Sub
...
On a separate module, I have the following function used to set my event handler
Public Sub AutoExec()
Set mxlApp = Application
Set ColectionOfMxlEventHandlers = New Collection
ColectionOfMxlEventHandlers.Add mxlApp
Debug.Print ThisWorkbook.Name & " Initialized"
End Sub
The problem: on the original .xlsm file, the code works fine: every time I right-click on a cell which meets certain criteria, I get the 'Run macro for XYZ' and all is fine.
Once I save the file as .xlam and load it as addin, the code won't work.
I have been looking everywhere on the internet and here and couldn't figure out how to resolve this issue.
EDIT:
After modifying the code as kindly suggested by creamyegg, this is what I have:
In class module clsAppEvents:
Private WithEvents mxlApp As Excel.Application
Private Sub Class_Initialize()
Set mxlApp = Excel.Application
End Sub
Private Sub mxlApp_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
Dim cBut As CommandBarButton
On Error Resume Next
Call CleanMenu
If Len(Target.Value) = 8 Then
MyId = Target.Value
With Application
Set cBut = .CommandBars("Cell").Controls.Add(Temporary:=True)
End With
With cBut
.Caption = "Run SQL Query for " & MyId
.Style = msoButtonCaption
.FaceId = 2554
.OnAction = "CallGenericQuery"
End With
End If
With Application
Set cBut = .CommandBars("Cell").Controls.Add(Temporary:=True)
End With
With cBut
.Caption = "Columns_Select"
.Style = msoButtonCaption
.FaceId = 255
.OnAction = "CallShowHide"
End With
On Error GoTo 0
End Sub
in Thisworkbook class I have
Public m_objMe As clsAppEvents
Private Sub Workbook_Open()
Set m_objMe = New clsAppEvents
Debug.Print ThisWorkbook.Name & " Initialized"
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
On Error Resume Next
Call CleanMenu
On Error GoTo 0
Set m_objMe = Nothing
End Sub
Private Sub Workbook_Deactivate()
Call CleanMenu
End Sub
MyId is defined as a public string in the main module containing the CallShowHide and callGenericQuery subs
The issue sounds like your WithEvents is still in your ThisWorkbook Class? What you need to do is create a new class and then instantiate an instance of this on the Workbook_Open() event of your add-in. For example:
New Class (clsAppEvents):
Private WithEvents mxlApp As Excel.Application
Private Sub Class_Initialize()
Set mxlApp = Excel.Application
End Sub
Private Sub mxlApp_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
...
End Sub
Add-in ThisWorkbook Class:
Private m_objMe As clsAppEvents
Private Sub Workbook_Open()
Set m_objMe = New clsAppEvents
End Sub
Private Sub WorkbookBeforeClose(Cancel As Boolean)
Set m_objMe = Nothing
End Sub

Resources