Milad
Milad

Reputation: 127

How to access a VBA Userform Button control code programmatically

I want whenever I click on my ActiveX command button on Sheet1 it open VBA Editor and jump directly to the code I wrote for a button on my userform. I know the way to jump directly to code for a module but I couldn't find a property for userform button control (something like ThisWorkbook.VBProject.VBComponents("UserForm1").Controls("MyButton"))

Following is my code for jumping right into my Madule1 code:

Private Sub CommandButton1_Click()

Dim Wb As Workbook: Set Wb = ThisWorkbook

'---Open Module1
Application.VBE.MainWindow.Visible = True
Wb.VBProject.VBComponents("UserForm1").Activate

End Sub

I thaught these pictures would help to better understand my goal:

1-I have an ActiveX command button on sheet1

enter image description here

2-I have userform with a commandbutton on it

enter image description here

3-This commandbuttun has it's own code which I want to jump to it's code

enter image description here

Upvotes: 0

Views: 626

Answers (1)

Christofer Weber
Christofer Weber

Reputation: 1474

If you want to jump to that specific sub directly, try this:

Private Sub CommandButton1_Click()

Application.VBE.ActiveVBProject.VBComponents("UserForm1").CodeModule.CodePane.Show

With Application.VBE.ActiveCodePane.CodeModule
    lStartLine = .ProcStartLine("CommandButton1_Click", 0) '"CommandButton1_Click" being the name of the sub you want.
    .CodePane.SetSelection lStartLine, 1, lStartLine, 1
End With

End Sub

First line should show you the code panel for the userform, and the second part selects the row down by the sub you are looking for by name.

Upvotes: 1

Related Questions