Search code examples
excelvbauserform

VBA EXCEL: Can I copy Userform's code to a txt file?


I would like to copy the code from a userform using a macro, but I couldn't find any way to do so, help, please.


Solution

  • This function will get the text of a userform, code module, or class module. You'll need the Microsoft VBA Extensibility 5.5 reference that @SHK mentioned.

    Function getCodeText(wb As Workbook, moduleName As String) As String
        Dim myCode As VBIDE.CodeModule
    
        Set myCode = wb.VBProject.VBComponents.Item(moduleName).CodeModule
        getCodeText = myCode.Lines(1, myCode.CountOfLines)
    End Function
    
    Sub testCall()
        MsgBox getCodeText(Workbooks("MyWorkbook.xlsm"), "MyUserformName")
    End Sub