0

I have a button called btnTest and i want to retrive a string as its click event (btnTest_Click), so i tried like below but with no results:

Private Sub btnTest_Click()

Dim strModule As String

strModule = Me.Application.VBE.ActiveCodePane.CodeModule.ProcOfLine(Me.Application.VBE.ActiveCodePane.TopLine, 0)

MsgBox strModule

End Sub

the msgbox has to display the string "btnTest_Click", i thought local variables can help too but i don't know how to manage them..

PS: This question was marked as duplicate of this thread that is error handling oriented, my question was not oriented for that purpose.. So I examinated that thread and i found a solution for my question that is much more versatile.

You can use this code in a module:

Public Function GetFnOrSubName(ObjName As Object, checkType As Boolean) As String

Dim VBProj As Object
Dim VBComp As Object
Dim CodeMod As Object

Set VBProj = Application.VBE.ActiveVBProject
Set VBComp = VBProj.VBComponents(ObjName.Application.VBE.CodePanes(2).CodeModule.Name)
Set CodeMod = VBComp.CodeModule

Dim code$
code = CodeMod.Lines(1, CodeMod.CountOfLines)

Dim CodeBlock
CodeBlock = InStr(1, code, ObjName.Name, vbTextCompare)
    
    
If CodeBlock Then

    Dim isFunction
    Dim isSub

    If checkType = True Then
        isFunction = InStrRev(Mid$(code, 1, CodeBlock), "Function", -1, vbTextCompare)
        isSub = InStrRev(Mid$(code, 1, CodeBlock), "Sub", -1, vbTextCompare)

    Else
        isFunction = InStrRev(Mid$(code, 1, CodeBlock), "Function", -1, vbTextCompare) + 8
        isSub = InStrRev(Mid$(code, 1, CodeBlock), "Sub", -1, vbTextCompare) + 3
    End If


    If isFunction > isSub Then
    ' it's a function
        GetFnOrSubName = Split(Mid$(code, isFunction, 40), "(")(0)
    Else
    ' it's a sub
        GetFnOrSubName = Split(Mid$(code, isSub, 40), "(")(0)
    
    End If

End If

End Function

You can test it in a button:

Private Sub btnTest_Click()

MsgBox GetFnOrSubName(Screen.ActiveControl, False)

End Sub

Hope this can help.

Alex
  • 113
  • 1
  • 14

0 Answers0