Using the function ShowAnyForm
of Cpearson this can be done with a class module.
An example with the following VBA project tree:
Form
An example with the following Form:
A form with two buttons with the name of the form that should be opened.
And with the following code:
Private collBtns As Collection
Private Sub UserForm_Initialize()
'Créditos: www.andypope.info
' www.cpearson.com/excel/Events.aspx
Dim cls_btn As Classe1
Set collBtns = New Collection
For Each ctrl In Me.Controls
If TypeName(ctrl) = "CommandButton" Then
Set cls_btn = New Classe1
Set cls_btn.btn = ctrl
collBtns.Add cls_btn, CStr(collBtns.Count + 1)
End If
Next ctrl
End Sub
Class module
This code is inserted in the class module Classe1
Public WithEvents btn As MSForms.CommandButton
Private Sub btn_Click()
ShowAnyForm (btn.Name)
End Sub
Private Sub ShowAnyForm(FormName As String, Optional Modal As FormShowConstants = vbModal)
'http://www.cpearson.com/Excel/showanyform.htm
Dim Obj As Object
For Each Obj In VBA.UserForms
If StrComp(Obj.Name, FormName, vbTextCompare) = 0 Then
Obj.Show Modal
Exit Sub
End If
Next Obj
With VBA.UserForms
On Error Resume Next
Err.Clear
Set Obj = .Add(FormName)
If Err.Number <> 0 Then
MsgBox "Err: " & CStr(Err.Number) & " " & Err.Description
Exit Sub
End If
Obj.Show Modal
End With
End Sub
In this, the button clicks event is declared in btn_Click()
.
That with the click of the button, will open the form of the same name of the Button with the function ShowAnyForm
.
The options you can use to display the form are vbModal
and vbModeless
Example:
Private Sub btn_Click()
ShowAnyForm btn.Name, vbModal
End Sub
Private Sub btn_Click()
ShowAnyForm btn.Name, vbModeless
End Sub
Upshot
I adapted in my design and it worked perfectly. Thank you very much
– user123166
Dear friend, how do I paste in the active userForm texbox1 the value of sheet A1? "Userformativo". textbox1.value = Sheets("plan1"). range("a1"). How do I declare the statement to mean "Active Userform"?
– user123166