Copy VBA code from one Worksheet to another using VBA code

前端 未结 2 661
独厮守ぢ
独厮守ぢ 2020-12-07 05:12

Ok here is what I want to accomplish: I am trying to copy all the VBA code from \"Sheet2\" to \"Sheet 3\" code pane. I\'m NOT referring to copying a Module from one to anoth

相关标签:
2条回答
  • 2020-12-07 05:36

    Use the CodeModule object instead of the CodePane, then you can create a second variable to represent the destination module (where you will "paste" the code).

    Sub test()
    
    Dim CodeCopy As VBIDE.CodeModule
    Dim CodePaste As VBIDE.CodeModule
    Dim numLines As Integer
    
    Set CodeCopy = ActiveWorkbook.VBProject.VBComponents("Sheet2").CodeModule
    Set CodePaste = ActiveWorkbook.VBProject.VBComponents("Sheet3").CodeModule
    
    numLines = CodeCopy.CountOfLines
    'Use this line to erase all code that might already be in sheet3:
    'If CodePaste.CountOfLines > 1 Then CodePaste.DeleteLines 1, CodePaste.CountOfLines
    
    CodePaste.AddFromString CodeCopy.Lines(1, numLines)
    End Sub
    

    In addition to adding a reference to "Reference to MS VB for Applications Extensibility 5.3"

    You'll also need to enable programmatic access to the VBA Project.

    In Excel 2007+, click the Developer item on the main Ribbon and then click the Macro Security item in the Code panel. In that dialog, choose Macro Settings and check the Trust access to the VBA project object model.

    0 讨论(0)
  • 2020-12-07 05:39

    Thank you all! After testing multiple suggestions above, where "b" is the Worksheet name, you must use .CodeName, NOT .Name

    Set CodePaste = ActiveWorkbook.VBProject.VBComponents(WorkShe‌ets(b).CodeName).Cod‌​eModule
    

    If you have set your target worksheet as an object:

    Dim T As Worksheet  
    Set T = Worksheets("Test")  
    

    Then you simply need:

    Set CodePaste = ActiveWorkbook.VBProject.VBComponents(Worksheets(T.Name).CodeName).Cod‌​eModule
    
    0 讨论(0)
提交回复
热议问题