VBA to copy Module from one Excel Workbook to another Workbook

前端 未结 5 1884
猫巷女王i
猫巷女王i 2020-12-29 12:16

I am trying to copy a module from one excel workbook to another using VBA.

My Code:

\'Copy Macros

Dim comp As Object
Set comp = ThisWorkbook.VBProje         


        
5条回答
  •  我在风中等你
    2020-12-29 13:05

    I had a lot of trouble getting the previous answers to work, so I thought I'd post my solution. This function is used to programmatically copy modules from a source workbook to a newly created workbook that was also created programmatically with a call to worksheet.copy. What doesn't happen when a worksheet is copied to a new workbook is the transfer of the macros that the worksheet depends upon. This procedure iterates through all modules in the source workbook and copies them into the new one. What's more is that it actually worked for me in Excel 2016.

    Sub CopyModules(wbSource As Workbook, wbTarget As Workbook)
       Dim vbcompSource As VBComponent, vbcompTarget As VBComponent
       Dim sText As String, nType As Long
       For Each vbcompSource In wbSource.VBProject.VBComponents
          nType = vbcompSource.Type
          If nType < 100 Then  '100=vbext_ct_Document -- the only module type we would not want to copy
             Set vbcompTarget = wbTarget.VBProject.VBComponents.Add(nType)
             sText = vbcompSource.CodeModule.Lines(1, vbcompSource.CodeModule.CountOfLines)
             vbcompTarget.CodeModule.AddFromString (sText)
             vbcompTarget.Name = vbcompSource.Name
          End If
       Next vbcompSource
    End Sub
    

    The function should hopefully be as simple as possible and fairly self-explanatory.

提交回复
热议问题