How to programmatically add code to a Sheet?

前端 未结 1 1716
一向
一向 2021-01-23 08:13

I have some code that I added to a Worksheet

Right Click on the Sheet1 -> View Code -> Paste my code to the Module

How can I do this prog

相关标签:
1条回答
  • 2021-01-23 09:16

    I would question your ultimate intent, since it may be more efficient to have a single copy of the code rather than a copy in each sheet, but....

    Sub AddCode()
        Dim ws As Worksheet: Set ws = Worksheets("sheet2")
        Dim wb As Workbook:  Set wb = ActiveWorkbook
        Dim code As String:  code = "Sub Duh()" & vbCrLf & " debug.print(""I'm Here!"")" & vbCrLf & "End Sub"
    
        Dim lineCount As Integer
    
        With wb.VBProject.VBComponents(ws.Name).CodeModule
            lineCount = .CountOfLines
            If lineCount > 0 Then
                .DeleteLines 1, lineCount
            End If
            .AddFromString code
        End With
    End Sub
    
    0 讨论(0)
提交回复
热议问题