VBA to copy Module from one Excel Workbook to another Workbook












4















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.VBProject.VBComponents("Module2")
Set Target = Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm").VBProject.VBComponents.Add(1)


For some reason, this copies the module, but does not copy the VBA code inside, why?



Please can someone show me where i am going wrong?



Thanks










share|improve this question

























  • Shouldn't you .Add(comp) ? There is no use for the comp object in your code otherwise

    – Jeremy Thompson
    Dec 4 '16 at 7:35













  • @JeremyThompson if i use comp it gives me object doesnt support this property or method error

    – Princess.Bell
    Dec 4 '16 at 7:39











  • Use the example here to get started. cpearson.com/excel/vbe.aspx

    – Tim Williams
    Dec 4 '16 at 8:30











  • @Bing.Wong try the code in my answer below and see if it works for you

    – Shai Rado
    Dec 4 '16 at 8:34
















4















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.VBProject.VBComponents("Module2")
Set Target = Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm").VBProject.VBComponents.Add(1)


For some reason, this copies the module, but does not copy the VBA code inside, why?



Please can someone show me where i am going wrong?



Thanks










share|improve this question

























  • Shouldn't you .Add(comp) ? There is no use for the comp object in your code otherwise

    – Jeremy Thompson
    Dec 4 '16 at 7:35













  • @JeremyThompson if i use comp it gives me object doesnt support this property or method error

    – Princess.Bell
    Dec 4 '16 at 7:39











  • Use the example here to get started. cpearson.com/excel/vbe.aspx

    – Tim Williams
    Dec 4 '16 at 8:30











  • @Bing.Wong try the code in my answer below and see if it works for you

    – Shai Rado
    Dec 4 '16 at 8:34














4












4








4


3






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.VBProject.VBComponents("Module2")
Set Target = Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm").VBProject.VBComponents.Add(1)


For some reason, this copies the module, but does not copy the VBA code inside, why?



Please can someone show me where i am going wrong?



Thanks










share|improve this question
















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.VBProject.VBComponents("Module2")
Set Target = Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm").VBProject.VBComponents.Add(1)


For some reason, this copies the module, but does not copy the VBA code inside, why?



Please can someone show me where i am going wrong?



Thanks







excel vba excel-vba






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 4 '16 at 8:42









Shai Rado

29.4k71530




29.4k71530










asked Dec 4 '16 at 7:32









Princess.BellPrincess.Bell

1381314




1381314













  • Shouldn't you .Add(comp) ? There is no use for the comp object in your code otherwise

    – Jeremy Thompson
    Dec 4 '16 at 7:35













  • @JeremyThompson if i use comp it gives me object doesnt support this property or method error

    – Princess.Bell
    Dec 4 '16 at 7:39











  • Use the example here to get started. cpearson.com/excel/vbe.aspx

    – Tim Williams
    Dec 4 '16 at 8:30











  • @Bing.Wong try the code in my answer below and see if it works for you

    – Shai Rado
    Dec 4 '16 at 8:34



















  • Shouldn't you .Add(comp) ? There is no use for the comp object in your code otherwise

    – Jeremy Thompson
    Dec 4 '16 at 7:35













  • @JeremyThompson if i use comp it gives me object doesnt support this property or method error

    – Princess.Bell
    Dec 4 '16 at 7:39











  • Use the example here to get started. cpearson.com/excel/vbe.aspx

    – Tim Williams
    Dec 4 '16 at 8:30











  • @Bing.Wong try the code in my answer below and see if it works for you

    – Shai Rado
    Dec 4 '16 at 8:34

















Shouldn't you .Add(comp) ? There is no use for the comp object in your code otherwise

– Jeremy Thompson
Dec 4 '16 at 7:35







Shouldn't you .Add(comp) ? There is no use for the comp object in your code otherwise

– Jeremy Thompson
Dec 4 '16 at 7:35















@JeremyThompson if i use comp it gives me object doesnt support this property or method error

– Princess.Bell
Dec 4 '16 at 7:39





@JeremyThompson if i use comp it gives me object doesnt support this property or method error

– Princess.Bell
Dec 4 '16 at 7:39













Use the example here to get started. cpearson.com/excel/vbe.aspx

– Tim Williams
Dec 4 '16 at 8:30





Use the example here to get started. cpearson.com/excel/vbe.aspx

– Tim Williams
Dec 4 '16 at 8:30













@Bing.Wong try the code in my answer below and see if it works for you

– Shai Rado
Dec 4 '16 at 8:34





@Bing.Wong try the code in my answer below and see if it works for you

– Shai Rado
Dec 4 '16 at 8:34












5 Answers
5






active

oldest

votes


















7














Sub CopyModule below, receives 3 parameters:



1.Source Workbook (as Workbook).



2.Module Name to Copy (as String).



3.Target Workbook (as Workbook).



CopyModule Code



Public Sub CopyModule(SourceWB As Workbook, strModuleName As String, TargetWB As Workbook)

' Description: copies a module from one workbook to another
' example: CopyModule Workbooks(ThisWorkbook), "Module2",
' Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm")
' Notes: If Module to be copied already exists, it is removed first,
' and afterwards copied

Dim strFolder As String
Dim strTempFile As String
Dim FName As String

If Trim(strModuleName) = vbNullString Then
Exit Sub
End If

If TargetWB Is Nothing Then
MsgBox "Error: Target Workbook " & TargetWB.Name & " doesn't exist (or closed)", vbCritical
Exit Sub
End If

strFolder = SourceWB.Path
If Len(strFolder) = 0 Then strFolder = CurDir

' create temp file and copy "Module2" into it
strFolder = strFolder & ""
strTempFile = strFolder & "~tmpexport.bas"

On Error Resume Next
FName = Environ("Temp") & "" & strModuleName & ".bas"
If Dir(FName, vbNormal + vbHidden + vbSystem) <> vbNullString Then
Err.Clear
Kill FName
If Err.Number <> 0 Then
MsgBox "Error copying module " & strModuleName & " from Workbook " & SourceWB.Name & " to Workbook " & TargetWB.Name, vbInformation
Exit Sub
End If
End If

' remove "Module2" if already exits in destination workbook
With TargetWB.VBProject.VBComponents
.Remove .Item(strModuleName)
End With

' copy "Module2" from temp file to destination workbook
SourceWB.VBProject.VBComponents(strModuleName).Export strTempFile
TargetWB.VBProject.VBComponents.Import strTempFile

Kill strTempFile
On Error GoTo 0

End Sub




Main Sub Code (for running this code with the Post's data):



Option Explicit

Public Sub Main()

Dim WB1 As Workbook
Dim WB2 As Workbook

Set WB1 = ThisWorkbook
Set WB2 = Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm")

Call CopyModule(WB1, "Module2", WB2)

End Sub





share|improve this answer


























  • Do you have to do it via Import/Export?

    – Jeremy Thompson
    Dec 4 '16 at 9:44











  • Didn't check to see other ways of implementing this need, I have been running this code (different versions of it) for a while now, and it's giving me the results I need

    – Shai Rado
    Dec 4 '16 at 9:47











  • No worries, just curious as to file seems like a lot of overhead and it does have an Add method

    – Jeremy Thompson
    Dec 4 '16 at 9:49











  • Feel free to send a link to another simplier and faster solution, always happy to learn and improve

    – Shai Rado
    Dec 4 '16 at 9:53






  • 1





    Haha, I upvoted about 30secs before commenting :)

    – Jeremy Thompson
    Dec 4 '16 at 11:24





















3














Fantastic Code by Chris Melville, Thanks a ton, just a few small addition which i did & added few comments.



Just make sure, following things are done before running this macro.




  • VB Editor > Tools > References > (Check) Microsoft Visual Basic for Applications Extensibility 5.3


  • File -> Options -> Trust Center -> Trust Center Setttings -> Macro Settings -> Trust Access to the VBA Project object model.



Once you do above thing, copy & paste below code in Source File



Sub CopyMacrosToExistingWorkbook()
'Copy this VBA Code in SourceMacroModule, & run this macro in Destination workbook by pressing Alt+F8, the whole module gets copied to destination File.
Dim SourceVBProject As VBIDE.VBProject, DestinationVBProject As VBIDE.VBProject
Set SourceVBProject = ThisWorkbook.VBProject
Dim NewWb As Workbook
Set NewWb = ActiveWorkbook ' Or whatever workbook object you have for the destination
Set DestinationVBProject = NewWb.VBProject
'
Dim SourceModule As VBIDE.CodeModule, DestinationModule As VBIDE.CodeModule
Set SourceModule = SourceVBProject.VBComponents("Module1").CodeModule ' Change "Module1" to the relevsant source module
' Add a new module to the destination project
Set DestinationModule = DestinationVBProject.VBComponents.Add(vbext_ct_StdModule).CodeModule
'
With SourceModule
DestinationModule.AddFromString .Lines(1, .CountOfLines)
End With
End Sub


Now run the "CopyMacrosToExistingWorkbook" macro in destination file, you will see the source file macro copied to destination file.






share|improve this answer


























  • To use AddFromString at once after creation seems not be well, because this might duplicate text Option Explicit if apropriate option is ON. Am first (after creation) you should delete all the lines in newly created module: DestinationModule.DeleteLines 1, DestinationModule.CountOfLines

    – Leon Rom
    Jan 6 '18 at 17:22



















2














Actually, you don't need to save anything to a temporary file at all. You can use the .AddFromString method of the destination module to add the string value of the source. Try the following code:



Sub CopyModule()
Dim SourceVBProject As VBIDE.VBProject, DestinationVBProject As VBIDE.VBProject
Set SourceVBProject = ThisWorkbook.VBProject
Dim NewWb As Workbook
Set NewWb = Workbooks.Add ' Or whatever workbook object you have for the destination
Set DestinationVBProject = NewWb.VBProject
'
Dim SourceModule As VBIDE.CodeModule, DestinationModule As VBIDE.CodeModule
Set SourceModule = SourceVBProject.VBComponents("Module1").CodeModule ' Change "Module1" to the relevsant source module
' Add a new module to the destination project
Set DestinationModule = DestinationVBProject.VBComponents.Add(vbext_ct_StdModule).CodeModule
'
With SourceModule
DestinationModule.AddFromString .Lines(1, .CountOfLines)
End With
End Sub


Should be self-explanatory! The .AddFomString method simply takes a string variable. So in order to get that, we use the .Lines property of the source module. The first argument (1) is the start line, and the second argument is the end line number. In this case, we want all the lines, so we use the .CountOfLines property.






share|improve this answer


























  • Using at once 'AddFromString' seems not be good, because it might duplicate text "Option Explicit" (if apropriate option is ON). Am first (after creation) I delete all the lines in 'DestinationModule'!

    – Leon Rom
    Jan 6 '18 at 14:56













  • @Yogendra gets honorable mention for specifying the Extensibility and Macro settings.

    – LeftyMaus
    Sep 4 '18 at 18:10





















1














Shai Rado's method of export/import has the advantage that you can split them, i.e. export the module from the source workbook as one step and then import them into multiple target files!






share|improve this answer
























  • what is the answer for copying also VBA code inside?

    – user7294900
    Jul 6 '17 at 6:57











  • Shai Rado's method is using export/import instead of the .Add method. it also imports the contents, the code inside the module.

    – Joe Phi
    Jul 6 '17 at 8:04





















0














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.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40956465%2fvba-to-copy-module-from-one-excel-workbook-to-another-workbook%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    5 Answers
    5






    active

    oldest

    votes








    5 Answers
    5






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    7














    Sub CopyModule below, receives 3 parameters:



    1.Source Workbook (as Workbook).



    2.Module Name to Copy (as String).



    3.Target Workbook (as Workbook).



    CopyModule Code



    Public Sub CopyModule(SourceWB As Workbook, strModuleName As String, TargetWB As Workbook)

    ' Description: copies a module from one workbook to another
    ' example: CopyModule Workbooks(ThisWorkbook), "Module2",
    ' Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm")
    ' Notes: If Module to be copied already exists, it is removed first,
    ' and afterwards copied

    Dim strFolder As String
    Dim strTempFile As String
    Dim FName As String

    If Trim(strModuleName) = vbNullString Then
    Exit Sub
    End If

    If TargetWB Is Nothing Then
    MsgBox "Error: Target Workbook " & TargetWB.Name & " doesn't exist (or closed)", vbCritical
    Exit Sub
    End If

    strFolder = SourceWB.Path
    If Len(strFolder) = 0 Then strFolder = CurDir

    ' create temp file and copy "Module2" into it
    strFolder = strFolder & ""
    strTempFile = strFolder & "~tmpexport.bas"

    On Error Resume Next
    FName = Environ("Temp") & "" & strModuleName & ".bas"
    If Dir(FName, vbNormal + vbHidden + vbSystem) <> vbNullString Then
    Err.Clear
    Kill FName
    If Err.Number <> 0 Then
    MsgBox "Error copying module " & strModuleName & " from Workbook " & SourceWB.Name & " to Workbook " & TargetWB.Name, vbInformation
    Exit Sub
    End If
    End If

    ' remove "Module2" if already exits in destination workbook
    With TargetWB.VBProject.VBComponents
    .Remove .Item(strModuleName)
    End With

    ' copy "Module2" from temp file to destination workbook
    SourceWB.VBProject.VBComponents(strModuleName).Export strTempFile
    TargetWB.VBProject.VBComponents.Import strTempFile

    Kill strTempFile
    On Error GoTo 0

    End Sub




    Main Sub Code (for running this code with the Post's data):



    Option Explicit

    Public Sub Main()

    Dim WB1 As Workbook
    Dim WB2 As Workbook

    Set WB1 = ThisWorkbook
    Set WB2 = Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm")

    Call CopyModule(WB1, "Module2", WB2)

    End Sub





    share|improve this answer


























    • Do you have to do it via Import/Export?

      – Jeremy Thompson
      Dec 4 '16 at 9:44











    • Didn't check to see other ways of implementing this need, I have been running this code (different versions of it) for a while now, and it's giving me the results I need

      – Shai Rado
      Dec 4 '16 at 9:47











    • No worries, just curious as to file seems like a lot of overhead and it does have an Add method

      – Jeremy Thompson
      Dec 4 '16 at 9:49











    • Feel free to send a link to another simplier and faster solution, always happy to learn and improve

      – Shai Rado
      Dec 4 '16 at 9:53






    • 1





      Haha, I upvoted about 30secs before commenting :)

      – Jeremy Thompson
      Dec 4 '16 at 11:24


















    7














    Sub CopyModule below, receives 3 parameters:



    1.Source Workbook (as Workbook).



    2.Module Name to Copy (as String).



    3.Target Workbook (as Workbook).



    CopyModule Code



    Public Sub CopyModule(SourceWB As Workbook, strModuleName As String, TargetWB As Workbook)

    ' Description: copies a module from one workbook to another
    ' example: CopyModule Workbooks(ThisWorkbook), "Module2",
    ' Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm")
    ' Notes: If Module to be copied already exists, it is removed first,
    ' and afterwards copied

    Dim strFolder As String
    Dim strTempFile As String
    Dim FName As String

    If Trim(strModuleName) = vbNullString Then
    Exit Sub
    End If

    If TargetWB Is Nothing Then
    MsgBox "Error: Target Workbook " & TargetWB.Name & " doesn't exist (or closed)", vbCritical
    Exit Sub
    End If

    strFolder = SourceWB.Path
    If Len(strFolder) = 0 Then strFolder = CurDir

    ' create temp file and copy "Module2" into it
    strFolder = strFolder & ""
    strTempFile = strFolder & "~tmpexport.bas"

    On Error Resume Next
    FName = Environ("Temp") & "" & strModuleName & ".bas"
    If Dir(FName, vbNormal + vbHidden + vbSystem) <> vbNullString Then
    Err.Clear
    Kill FName
    If Err.Number <> 0 Then
    MsgBox "Error copying module " & strModuleName & " from Workbook " & SourceWB.Name & " to Workbook " & TargetWB.Name, vbInformation
    Exit Sub
    End If
    End If

    ' remove "Module2" if already exits in destination workbook
    With TargetWB.VBProject.VBComponents
    .Remove .Item(strModuleName)
    End With

    ' copy "Module2" from temp file to destination workbook
    SourceWB.VBProject.VBComponents(strModuleName).Export strTempFile
    TargetWB.VBProject.VBComponents.Import strTempFile

    Kill strTempFile
    On Error GoTo 0

    End Sub




    Main Sub Code (for running this code with the Post's data):



    Option Explicit

    Public Sub Main()

    Dim WB1 As Workbook
    Dim WB2 As Workbook

    Set WB1 = ThisWorkbook
    Set WB2 = Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm")

    Call CopyModule(WB1, "Module2", WB2)

    End Sub





    share|improve this answer


























    • Do you have to do it via Import/Export?

      – Jeremy Thompson
      Dec 4 '16 at 9:44











    • Didn't check to see other ways of implementing this need, I have been running this code (different versions of it) for a while now, and it's giving me the results I need

      – Shai Rado
      Dec 4 '16 at 9:47











    • No worries, just curious as to file seems like a lot of overhead and it does have an Add method

      – Jeremy Thompson
      Dec 4 '16 at 9:49











    • Feel free to send a link to another simplier and faster solution, always happy to learn and improve

      – Shai Rado
      Dec 4 '16 at 9:53






    • 1





      Haha, I upvoted about 30secs before commenting :)

      – Jeremy Thompson
      Dec 4 '16 at 11:24
















    7












    7








    7







    Sub CopyModule below, receives 3 parameters:



    1.Source Workbook (as Workbook).



    2.Module Name to Copy (as String).



    3.Target Workbook (as Workbook).



    CopyModule Code



    Public Sub CopyModule(SourceWB As Workbook, strModuleName As String, TargetWB As Workbook)

    ' Description: copies a module from one workbook to another
    ' example: CopyModule Workbooks(ThisWorkbook), "Module2",
    ' Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm")
    ' Notes: If Module to be copied already exists, it is removed first,
    ' and afterwards copied

    Dim strFolder As String
    Dim strTempFile As String
    Dim FName As String

    If Trim(strModuleName) = vbNullString Then
    Exit Sub
    End If

    If TargetWB Is Nothing Then
    MsgBox "Error: Target Workbook " & TargetWB.Name & " doesn't exist (or closed)", vbCritical
    Exit Sub
    End If

    strFolder = SourceWB.Path
    If Len(strFolder) = 0 Then strFolder = CurDir

    ' create temp file and copy "Module2" into it
    strFolder = strFolder & ""
    strTempFile = strFolder & "~tmpexport.bas"

    On Error Resume Next
    FName = Environ("Temp") & "" & strModuleName & ".bas"
    If Dir(FName, vbNormal + vbHidden + vbSystem) <> vbNullString Then
    Err.Clear
    Kill FName
    If Err.Number <> 0 Then
    MsgBox "Error copying module " & strModuleName & " from Workbook " & SourceWB.Name & " to Workbook " & TargetWB.Name, vbInformation
    Exit Sub
    End If
    End If

    ' remove "Module2" if already exits in destination workbook
    With TargetWB.VBProject.VBComponents
    .Remove .Item(strModuleName)
    End With

    ' copy "Module2" from temp file to destination workbook
    SourceWB.VBProject.VBComponents(strModuleName).Export strTempFile
    TargetWB.VBProject.VBComponents.Import strTempFile

    Kill strTempFile
    On Error GoTo 0

    End Sub




    Main Sub Code (for running this code with the Post's data):



    Option Explicit

    Public Sub Main()

    Dim WB1 As Workbook
    Dim WB2 As Workbook

    Set WB1 = ThisWorkbook
    Set WB2 = Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm")

    Call CopyModule(WB1, "Module2", WB2)

    End Sub





    share|improve this answer















    Sub CopyModule below, receives 3 parameters:



    1.Source Workbook (as Workbook).



    2.Module Name to Copy (as String).



    3.Target Workbook (as Workbook).



    CopyModule Code



    Public Sub CopyModule(SourceWB As Workbook, strModuleName As String, TargetWB As Workbook)

    ' Description: copies a module from one workbook to another
    ' example: CopyModule Workbooks(ThisWorkbook), "Module2",
    ' Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm")
    ' Notes: If Module to be copied already exists, it is removed first,
    ' and afterwards copied

    Dim strFolder As String
    Dim strTempFile As String
    Dim FName As String

    If Trim(strModuleName) = vbNullString Then
    Exit Sub
    End If

    If TargetWB Is Nothing Then
    MsgBox "Error: Target Workbook " & TargetWB.Name & " doesn't exist (or closed)", vbCritical
    Exit Sub
    End If

    strFolder = SourceWB.Path
    If Len(strFolder) = 0 Then strFolder = CurDir

    ' create temp file and copy "Module2" into it
    strFolder = strFolder & ""
    strTempFile = strFolder & "~tmpexport.bas"

    On Error Resume Next
    FName = Environ("Temp") & "" & strModuleName & ".bas"
    If Dir(FName, vbNormal + vbHidden + vbSystem) <> vbNullString Then
    Err.Clear
    Kill FName
    If Err.Number <> 0 Then
    MsgBox "Error copying module " & strModuleName & " from Workbook " & SourceWB.Name & " to Workbook " & TargetWB.Name, vbInformation
    Exit Sub
    End If
    End If

    ' remove "Module2" if already exits in destination workbook
    With TargetWB.VBProject.VBComponents
    .Remove .Item(strModuleName)
    End With

    ' copy "Module2" from temp file to destination workbook
    SourceWB.VBProject.VBComponents(strModuleName).Export strTempFile
    TargetWB.VBProject.VBComponents.Import strTempFile

    Kill strTempFile
    On Error GoTo 0

    End Sub




    Main Sub Code (for running this code with the Post's data):



    Option Explicit

    Public Sub Main()

    Dim WB1 As Workbook
    Dim WB2 As Workbook

    Set WB1 = ThisWorkbook
    Set WB2 = Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm")

    Call CopyModule(WB1, "Module2", WB2)

    End Sub






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Dec 4 '16 at 8:38

























    answered Dec 4 '16 at 8:31









    Shai RadoShai Rado

    29.4k71530




    29.4k71530













    • Do you have to do it via Import/Export?

      – Jeremy Thompson
      Dec 4 '16 at 9:44











    • Didn't check to see other ways of implementing this need, I have been running this code (different versions of it) for a while now, and it's giving me the results I need

      – Shai Rado
      Dec 4 '16 at 9:47











    • No worries, just curious as to file seems like a lot of overhead and it does have an Add method

      – Jeremy Thompson
      Dec 4 '16 at 9:49











    • Feel free to send a link to another simplier and faster solution, always happy to learn and improve

      – Shai Rado
      Dec 4 '16 at 9:53






    • 1





      Haha, I upvoted about 30secs before commenting :)

      – Jeremy Thompson
      Dec 4 '16 at 11:24





















    • Do you have to do it via Import/Export?

      – Jeremy Thompson
      Dec 4 '16 at 9:44











    • Didn't check to see other ways of implementing this need, I have been running this code (different versions of it) for a while now, and it's giving me the results I need

      – Shai Rado
      Dec 4 '16 at 9:47











    • No worries, just curious as to file seems like a lot of overhead and it does have an Add method

      – Jeremy Thompson
      Dec 4 '16 at 9:49











    • Feel free to send a link to another simplier and faster solution, always happy to learn and improve

      – Shai Rado
      Dec 4 '16 at 9:53






    • 1





      Haha, I upvoted about 30secs before commenting :)

      – Jeremy Thompson
      Dec 4 '16 at 11:24



















    Do you have to do it via Import/Export?

    – Jeremy Thompson
    Dec 4 '16 at 9:44





    Do you have to do it via Import/Export?

    – Jeremy Thompson
    Dec 4 '16 at 9:44













    Didn't check to see other ways of implementing this need, I have been running this code (different versions of it) for a while now, and it's giving me the results I need

    – Shai Rado
    Dec 4 '16 at 9:47





    Didn't check to see other ways of implementing this need, I have been running this code (different versions of it) for a while now, and it's giving me the results I need

    – Shai Rado
    Dec 4 '16 at 9:47













    No worries, just curious as to file seems like a lot of overhead and it does have an Add method

    – Jeremy Thompson
    Dec 4 '16 at 9:49





    No worries, just curious as to file seems like a lot of overhead and it does have an Add method

    – Jeremy Thompson
    Dec 4 '16 at 9:49













    Feel free to send a link to another simplier and faster solution, always happy to learn and improve

    – Shai Rado
    Dec 4 '16 at 9:53





    Feel free to send a link to another simplier and faster solution, always happy to learn and improve

    – Shai Rado
    Dec 4 '16 at 9:53




    1




    1





    Haha, I upvoted about 30secs before commenting :)

    – Jeremy Thompson
    Dec 4 '16 at 11:24







    Haha, I upvoted about 30secs before commenting :)

    – Jeremy Thompson
    Dec 4 '16 at 11:24















    3














    Fantastic Code by Chris Melville, Thanks a ton, just a few small addition which i did & added few comments.



    Just make sure, following things are done before running this macro.




    • VB Editor > Tools > References > (Check) Microsoft Visual Basic for Applications Extensibility 5.3


    • File -> Options -> Trust Center -> Trust Center Setttings -> Macro Settings -> Trust Access to the VBA Project object model.



    Once you do above thing, copy & paste below code in Source File



    Sub CopyMacrosToExistingWorkbook()
    'Copy this VBA Code in SourceMacroModule, & run this macro in Destination workbook by pressing Alt+F8, the whole module gets copied to destination File.
    Dim SourceVBProject As VBIDE.VBProject, DestinationVBProject As VBIDE.VBProject
    Set SourceVBProject = ThisWorkbook.VBProject
    Dim NewWb As Workbook
    Set NewWb = ActiveWorkbook ' Or whatever workbook object you have for the destination
    Set DestinationVBProject = NewWb.VBProject
    '
    Dim SourceModule As VBIDE.CodeModule, DestinationModule As VBIDE.CodeModule
    Set SourceModule = SourceVBProject.VBComponents("Module1").CodeModule ' Change "Module1" to the relevsant source module
    ' Add a new module to the destination project
    Set DestinationModule = DestinationVBProject.VBComponents.Add(vbext_ct_StdModule).CodeModule
    '
    With SourceModule
    DestinationModule.AddFromString .Lines(1, .CountOfLines)
    End With
    End Sub


    Now run the "CopyMacrosToExistingWorkbook" macro in destination file, you will see the source file macro copied to destination file.






    share|improve this answer


























    • To use AddFromString at once after creation seems not be well, because this might duplicate text Option Explicit if apropriate option is ON. Am first (after creation) you should delete all the lines in newly created module: DestinationModule.DeleteLines 1, DestinationModule.CountOfLines

      – Leon Rom
      Jan 6 '18 at 17:22
















    3














    Fantastic Code by Chris Melville, Thanks a ton, just a few small addition which i did & added few comments.



    Just make sure, following things are done before running this macro.




    • VB Editor > Tools > References > (Check) Microsoft Visual Basic for Applications Extensibility 5.3


    • File -> Options -> Trust Center -> Trust Center Setttings -> Macro Settings -> Trust Access to the VBA Project object model.



    Once you do above thing, copy & paste below code in Source File



    Sub CopyMacrosToExistingWorkbook()
    'Copy this VBA Code in SourceMacroModule, & run this macro in Destination workbook by pressing Alt+F8, the whole module gets copied to destination File.
    Dim SourceVBProject As VBIDE.VBProject, DestinationVBProject As VBIDE.VBProject
    Set SourceVBProject = ThisWorkbook.VBProject
    Dim NewWb As Workbook
    Set NewWb = ActiveWorkbook ' Or whatever workbook object you have for the destination
    Set DestinationVBProject = NewWb.VBProject
    '
    Dim SourceModule As VBIDE.CodeModule, DestinationModule As VBIDE.CodeModule
    Set SourceModule = SourceVBProject.VBComponents("Module1").CodeModule ' Change "Module1" to the relevsant source module
    ' Add a new module to the destination project
    Set DestinationModule = DestinationVBProject.VBComponents.Add(vbext_ct_StdModule).CodeModule
    '
    With SourceModule
    DestinationModule.AddFromString .Lines(1, .CountOfLines)
    End With
    End Sub


    Now run the "CopyMacrosToExistingWorkbook" macro in destination file, you will see the source file macro copied to destination file.






    share|improve this answer


























    • To use AddFromString at once after creation seems not be well, because this might duplicate text Option Explicit if apropriate option is ON. Am first (after creation) you should delete all the lines in newly created module: DestinationModule.DeleteLines 1, DestinationModule.CountOfLines

      – Leon Rom
      Jan 6 '18 at 17:22














    3












    3








    3







    Fantastic Code by Chris Melville, Thanks a ton, just a few small addition which i did & added few comments.



    Just make sure, following things are done before running this macro.




    • VB Editor > Tools > References > (Check) Microsoft Visual Basic for Applications Extensibility 5.3


    • File -> Options -> Trust Center -> Trust Center Setttings -> Macro Settings -> Trust Access to the VBA Project object model.



    Once you do above thing, copy & paste below code in Source File



    Sub CopyMacrosToExistingWorkbook()
    'Copy this VBA Code in SourceMacroModule, & run this macro in Destination workbook by pressing Alt+F8, the whole module gets copied to destination File.
    Dim SourceVBProject As VBIDE.VBProject, DestinationVBProject As VBIDE.VBProject
    Set SourceVBProject = ThisWorkbook.VBProject
    Dim NewWb As Workbook
    Set NewWb = ActiveWorkbook ' Or whatever workbook object you have for the destination
    Set DestinationVBProject = NewWb.VBProject
    '
    Dim SourceModule As VBIDE.CodeModule, DestinationModule As VBIDE.CodeModule
    Set SourceModule = SourceVBProject.VBComponents("Module1").CodeModule ' Change "Module1" to the relevsant source module
    ' Add a new module to the destination project
    Set DestinationModule = DestinationVBProject.VBComponents.Add(vbext_ct_StdModule).CodeModule
    '
    With SourceModule
    DestinationModule.AddFromString .Lines(1, .CountOfLines)
    End With
    End Sub


    Now run the "CopyMacrosToExistingWorkbook" macro in destination file, you will see the source file macro copied to destination file.






    share|improve this answer















    Fantastic Code by Chris Melville, Thanks a ton, just a few small addition which i did & added few comments.



    Just make sure, following things are done before running this macro.




    • VB Editor > Tools > References > (Check) Microsoft Visual Basic for Applications Extensibility 5.3


    • File -> Options -> Trust Center -> Trust Center Setttings -> Macro Settings -> Trust Access to the VBA Project object model.



    Once you do above thing, copy & paste below code in Source File



    Sub CopyMacrosToExistingWorkbook()
    'Copy this VBA Code in SourceMacroModule, & run this macro in Destination workbook by pressing Alt+F8, the whole module gets copied to destination File.
    Dim SourceVBProject As VBIDE.VBProject, DestinationVBProject As VBIDE.VBProject
    Set SourceVBProject = ThisWorkbook.VBProject
    Dim NewWb As Workbook
    Set NewWb = ActiveWorkbook ' Or whatever workbook object you have for the destination
    Set DestinationVBProject = NewWb.VBProject
    '
    Dim SourceModule As VBIDE.CodeModule, DestinationModule As VBIDE.CodeModule
    Set SourceModule = SourceVBProject.VBComponents("Module1").CodeModule ' Change "Module1" to the relevsant source module
    ' Add a new module to the destination project
    Set DestinationModule = DestinationVBProject.VBComponents.Add(vbext_ct_StdModule).CodeModule
    '
    With SourceModule
    DestinationModule.AddFromString .Lines(1, .CountOfLines)
    End With
    End Sub


    Now run the "CopyMacrosToExistingWorkbook" macro in destination file, you will see the source file macro copied to destination file.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 19 '18 at 9:26









    Paul Siersma

    629817




    629817










    answered Aug 15 '17 at 18:21









    YogendraYogendra

    311




    311













    • To use AddFromString at once after creation seems not be well, because this might duplicate text Option Explicit if apropriate option is ON. Am first (after creation) you should delete all the lines in newly created module: DestinationModule.DeleteLines 1, DestinationModule.CountOfLines

      – Leon Rom
      Jan 6 '18 at 17:22



















    • To use AddFromString at once after creation seems not be well, because this might duplicate text Option Explicit if apropriate option is ON. Am first (after creation) you should delete all the lines in newly created module: DestinationModule.DeleteLines 1, DestinationModule.CountOfLines

      – Leon Rom
      Jan 6 '18 at 17:22

















    To use AddFromString at once after creation seems not be well, because this might duplicate text Option Explicit if apropriate option is ON. Am first (after creation) you should delete all the lines in newly created module: DestinationModule.DeleteLines 1, DestinationModule.CountOfLines

    – Leon Rom
    Jan 6 '18 at 17:22





    To use AddFromString at once after creation seems not be well, because this might duplicate text Option Explicit if apropriate option is ON. Am first (after creation) you should delete all the lines in newly created module: DestinationModule.DeleteLines 1, DestinationModule.CountOfLines

    – Leon Rom
    Jan 6 '18 at 17:22











    2














    Actually, you don't need to save anything to a temporary file at all. You can use the .AddFromString method of the destination module to add the string value of the source. Try the following code:



    Sub CopyModule()
    Dim SourceVBProject As VBIDE.VBProject, DestinationVBProject As VBIDE.VBProject
    Set SourceVBProject = ThisWorkbook.VBProject
    Dim NewWb As Workbook
    Set NewWb = Workbooks.Add ' Or whatever workbook object you have for the destination
    Set DestinationVBProject = NewWb.VBProject
    '
    Dim SourceModule As VBIDE.CodeModule, DestinationModule As VBIDE.CodeModule
    Set SourceModule = SourceVBProject.VBComponents("Module1").CodeModule ' Change "Module1" to the relevsant source module
    ' Add a new module to the destination project
    Set DestinationModule = DestinationVBProject.VBComponents.Add(vbext_ct_StdModule).CodeModule
    '
    With SourceModule
    DestinationModule.AddFromString .Lines(1, .CountOfLines)
    End With
    End Sub


    Should be self-explanatory! The .AddFomString method simply takes a string variable. So in order to get that, we use the .Lines property of the source module. The first argument (1) is the start line, and the second argument is the end line number. In this case, we want all the lines, so we use the .CountOfLines property.






    share|improve this answer


























    • Using at once 'AddFromString' seems not be good, because it might duplicate text "Option Explicit" (if apropriate option is ON). Am first (after creation) I delete all the lines in 'DestinationModule'!

      – Leon Rom
      Jan 6 '18 at 14:56













    • @Yogendra gets honorable mention for specifying the Extensibility and Macro settings.

      – LeftyMaus
      Sep 4 '18 at 18:10


















    2














    Actually, you don't need to save anything to a temporary file at all. You can use the .AddFromString method of the destination module to add the string value of the source. Try the following code:



    Sub CopyModule()
    Dim SourceVBProject As VBIDE.VBProject, DestinationVBProject As VBIDE.VBProject
    Set SourceVBProject = ThisWorkbook.VBProject
    Dim NewWb As Workbook
    Set NewWb = Workbooks.Add ' Or whatever workbook object you have for the destination
    Set DestinationVBProject = NewWb.VBProject
    '
    Dim SourceModule As VBIDE.CodeModule, DestinationModule As VBIDE.CodeModule
    Set SourceModule = SourceVBProject.VBComponents("Module1").CodeModule ' Change "Module1" to the relevsant source module
    ' Add a new module to the destination project
    Set DestinationModule = DestinationVBProject.VBComponents.Add(vbext_ct_StdModule).CodeModule
    '
    With SourceModule
    DestinationModule.AddFromString .Lines(1, .CountOfLines)
    End With
    End Sub


    Should be self-explanatory! The .AddFomString method simply takes a string variable. So in order to get that, we use the .Lines property of the source module. The first argument (1) is the start line, and the second argument is the end line number. In this case, we want all the lines, so we use the .CountOfLines property.






    share|improve this answer


























    • Using at once 'AddFromString' seems not be good, because it might duplicate text "Option Explicit" (if apropriate option is ON). Am first (after creation) I delete all the lines in 'DestinationModule'!

      – Leon Rom
      Jan 6 '18 at 14:56













    • @Yogendra gets honorable mention for specifying the Extensibility and Macro settings.

      – LeftyMaus
      Sep 4 '18 at 18:10
















    2












    2








    2







    Actually, you don't need to save anything to a temporary file at all. You can use the .AddFromString method of the destination module to add the string value of the source. Try the following code:



    Sub CopyModule()
    Dim SourceVBProject As VBIDE.VBProject, DestinationVBProject As VBIDE.VBProject
    Set SourceVBProject = ThisWorkbook.VBProject
    Dim NewWb As Workbook
    Set NewWb = Workbooks.Add ' Or whatever workbook object you have for the destination
    Set DestinationVBProject = NewWb.VBProject
    '
    Dim SourceModule As VBIDE.CodeModule, DestinationModule As VBIDE.CodeModule
    Set SourceModule = SourceVBProject.VBComponents("Module1").CodeModule ' Change "Module1" to the relevsant source module
    ' Add a new module to the destination project
    Set DestinationModule = DestinationVBProject.VBComponents.Add(vbext_ct_StdModule).CodeModule
    '
    With SourceModule
    DestinationModule.AddFromString .Lines(1, .CountOfLines)
    End With
    End Sub


    Should be self-explanatory! The .AddFomString method simply takes a string variable. So in order to get that, we use the .Lines property of the source module. The first argument (1) is the start line, and the second argument is the end line number. In this case, we want all the lines, so we use the .CountOfLines property.






    share|improve this answer















    Actually, you don't need to save anything to a temporary file at all. You can use the .AddFromString method of the destination module to add the string value of the source. Try the following code:



    Sub CopyModule()
    Dim SourceVBProject As VBIDE.VBProject, DestinationVBProject As VBIDE.VBProject
    Set SourceVBProject = ThisWorkbook.VBProject
    Dim NewWb As Workbook
    Set NewWb = Workbooks.Add ' Or whatever workbook object you have for the destination
    Set DestinationVBProject = NewWb.VBProject
    '
    Dim SourceModule As VBIDE.CodeModule, DestinationModule As VBIDE.CodeModule
    Set SourceModule = SourceVBProject.VBComponents("Module1").CodeModule ' Change "Module1" to the relevsant source module
    ' Add a new module to the destination project
    Set DestinationModule = DestinationVBProject.VBComponents.Add(vbext_ct_StdModule).CodeModule
    '
    With SourceModule
    DestinationModule.AddFromString .Lines(1, .CountOfLines)
    End With
    End Sub


    Should be self-explanatory! The .AddFomString method simply takes a string variable. So in order to get that, we use the .Lines property of the source module. The first argument (1) is the start line, and the second argument is the end line number. In this case, we want all the lines, so we use the .CountOfLines property.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 18 '18 at 5:29









    ashleedawg

    12.8k42452




    12.8k42452










    answered Dec 4 '16 at 21:10









    Chris MelvilleChris Melville

    892314




    892314













    • Using at once 'AddFromString' seems not be good, because it might duplicate text "Option Explicit" (if apropriate option is ON). Am first (after creation) I delete all the lines in 'DestinationModule'!

      – Leon Rom
      Jan 6 '18 at 14:56













    • @Yogendra gets honorable mention for specifying the Extensibility and Macro settings.

      – LeftyMaus
      Sep 4 '18 at 18:10





















    • Using at once 'AddFromString' seems not be good, because it might duplicate text "Option Explicit" (if apropriate option is ON). Am first (after creation) I delete all the lines in 'DestinationModule'!

      – Leon Rom
      Jan 6 '18 at 14:56













    • @Yogendra gets honorable mention for specifying the Extensibility and Macro settings.

      – LeftyMaus
      Sep 4 '18 at 18:10



















    Using at once 'AddFromString' seems not be good, because it might duplicate text "Option Explicit" (if apropriate option is ON). Am first (after creation) I delete all the lines in 'DestinationModule'!

    – Leon Rom
    Jan 6 '18 at 14:56







    Using at once 'AddFromString' seems not be good, because it might duplicate text "Option Explicit" (if apropriate option is ON). Am first (after creation) I delete all the lines in 'DestinationModule'!

    – Leon Rom
    Jan 6 '18 at 14:56















    @Yogendra gets honorable mention for specifying the Extensibility and Macro settings.

    – LeftyMaus
    Sep 4 '18 at 18:10







    @Yogendra gets honorable mention for specifying the Extensibility and Macro settings.

    – LeftyMaus
    Sep 4 '18 at 18:10













    1














    Shai Rado's method of export/import has the advantage that you can split them, i.e. export the module from the source workbook as one step and then import them into multiple target files!






    share|improve this answer
























    • what is the answer for copying also VBA code inside?

      – user7294900
      Jul 6 '17 at 6:57











    • Shai Rado's method is using export/import instead of the .Add method. it also imports the contents, the code inside the module.

      – Joe Phi
      Jul 6 '17 at 8:04


















    1














    Shai Rado's method of export/import has the advantage that you can split them, i.e. export the module from the source workbook as one step and then import them into multiple target files!






    share|improve this answer
























    • what is the answer for copying also VBA code inside?

      – user7294900
      Jul 6 '17 at 6:57











    • Shai Rado's method is using export/import instead of the .Add method. it also imports the contents, the code inside the module.

      – Joe Phi
      Jul 6 '17 at 8:04
















    1












    1








    1







    Shai Rado's method of export/import has the advantage that you can split them, i.e. export the module from the source workbook as one step and then import them into multiple target files!






    share|improve this answer













    Shai Rado's method of export/import has the advantage that you can split them, i.e. export the module from the source workbook as one step and then import them into multiple target files!







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jul 6 '17 at 6:36









    Joe PhiJoe Phi

    12011




    12011













    • what is the answer for copying also VBA code inside?

      – user7294900
      Jul 6 '17 at 6:57











    • Shai Rado's method is using export/import instead of the .Add method. it also imports the contents, the code inside the module.

      – Joe Phi
      Jul 6 '17 at 8:04





















    • what is the answer for copying also VBA code inside?

      – user7294900
      Jul 6 '17 at 6:57











    • Shai Rado's method is using export/import instead of the .Add method. it also imports the contents, the code inside the module.

      – Joe Phi
      Jul 6 '17 at 8:04



















    what is the answer for copying also VBA code inside?

    – user7294900
    Jul 6 '17 at 6:57





    what is the answer for copying also VBA code inside?

    – user7294900
    Jul 6 '17 at 6:57













    Shai Rado's method is using export/import instead of the .Add method. it also imports the contents, the code inside the module.

    – Joe Phi
    Jul 6 '17 at 8:04







    Shai Rado's method is using export/import instead of the .Add method. it also imports the contents, the code inside the module.

    – Joe Phi
    Jul 6 '17 at 8:04













    0














    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.






    share|improve this answer




























      0














      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.






      share|improve this answer


























        0












        0








        0







        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 25 '18 at 6:05









        Sean HareSean Hare

        11




        11






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40956465%2fvba-to-copy-module-from-one-excel-workbook-to-another-workbook%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Wiesbaden

            Marschland

            Dieringhausen