Excel vba add code to sheet module programmatically

前端 未结 1 665
星月不相逢
星月不相逢 2020-11-27 19:28

How to put the programmatically generated workbook an event code similar to below:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim nextTarget As         


        
相关标签:
1条回答
  • 2020-11-27 20:24

    Use this to add a workbook and place a worksheet change event into the Sheet1 module.

    Sub AddSht_AddCode()
        Dim wb As Workbook
        Dim xPro As VBIDE.VBProject
        Dim xCom As VBIDE.VBComponent
        Dim xMod As VBIDE.CodeModule
        Dim xLine As Long
    
        Set wb = Workbooks.Add
    
        With wb
            Set xPro = .VBProject
            Set xCom = xPro.VBComponents("Sheet1")
            Set xMod = xCom.CodeModule
    
            With xMod
                xLine = .CreateEventProc("Change", "Worksheet")
                xLine = xLine + 1
                .InsertLines xLine, "  Cells.Columns.AutoFit"
            End With
        End With
    
    End Sub
    

    When you 1st run the code you may get an error.

    Hit the Stop Icon and select the tools menu and "References"

    Then find "Microsoft Visual Basic for Applications Extensibility 5.3 library" and check it.

    Run the code again and it should work.

    0 讨论(0)
提交回复
热议问题