TimRicta
TimRicta

Reputation: 135

Get the CommandButton Number from which the Click-Method was called

I have created a bunch of Commandbuttons with my class clsComamndButtons in a Userform. Everything works so far. All these Buttons should do the same, but i don't know how can i get the Name of the Button from which i called the cmdCommandButton_Click Method. I want to write the Path of the choosen folder in different cells, depending on the Button which was clicked.

This is my class clsCommandButtons:

Option Explicit

Public WithEvents cmdCommandButton As MSForms.CommandButton
Private msOnAction As String
Private mobjParent As Object

Public Property Get Object() As MSForms.CommandButton
    Set Object = cmdCommandButton
End Property

Public Function Load(ByVal parentFormName As Object, ByVal btn As MSForms.CommandButton, ByVal procedure As String) As clsCommandButtons
    Set mobjParent = parentFormName
    Set cmdCommandButton = btn
    msOnAction = procedure
    Set Load = Me
End Function

Private Sub Class_Terminate()
    Set mobjParent = Nothing
    Set cmdCommandButton = Nothing
End Sub


Private Sub cmdCommandButton_Click()
    Dim sFilepath       As String                       'Pfad der gewählten .txt-Filterdatei

    'Datei öffnen - Dialog
    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .InitialFileName = ActiveWorkbook.Path & "\"
        .Filters.Add "TextFiles", "*.txt", 1
        .FilterIndex = 1
        If .Show = -1 Then
            sFilepath = .SelectedItems(1)
        End If
    End With

    Cells(Row+???Depening on the Button which was clicked), constClmn) = sFilepath
End Sub

Upvotes: 1

Views: 323

Answers (2)

Vityata
Vityata

Reputation: 43585

In general, to get the row of the button, usae the BottomRightCell property or TopLeftCell depending on what you what you need.

If you are using ActiveX buttons (generally advised) then something like this should be ok:


Private Sub CommandButton1_Click()
    Debug.Print CommandButton1.BottomRightCell.Row
End Sub

If you are using Form elements, then assign the button-event to this and see:

Public Sub GetTheButtonName()
    Debug.Print "My name is ... "
    Debug.Print Buttons(Application.Caller).Name
    Debug.Print Buttons(Application.Caller).BottomRightCell.Row
End Sub

Upvotes: 0

Nathan_Sav
Nathan_Sav

Reputation: 8531

use the .name property cmdCommandButton.name

Upvotes: 1

Related Questions