+ Reply to Thread
Results 1 to 9 of 9

Copying VBA Modules Between Workbooks

Hybrid View

Jenn68 Copying VBA Modules Between... 01-18-2019, 03:09 PM
Logit Re: Copying VBA Modules... 01-18-2019, 09:24 PM
Andy Pope Re: Copying VBA Modules... 01-19-2019, 05:13 AM
Jenn68 Re: Copying VBA Modules... 01-19-2019, 07:00 PM
Jenn68 Re: Copying VBA Modules... 01-20-2019, 05:53 PM
Logit Re: Copying VBA Modules... 01-20-2019, 06:56 PM
Jenn68 Re: Copying VBA Modules... 01-22-2019, 11:57 AM
Andy Pope Re: Copying VBA Modules... 01-22-2019, 12:37 PM
Jenn68 Re: Copying VBA Modules... 01-22-2019, 01:24 PM
  1. #1
    Forum Contributor
    Join Date
    06-15-2009
    Location
    Ontario, canada
    MS-Off Ver
    Office 365
    Posts
    371

    Copying VBA Modules Between Workbooks

    This is a cross posting of a post I have made at another site. I suspect I may have challenged that group as there hasn't been much along the line of support. Perhaps there is no solution. I thought I'd post here to tap into the skill of a different group hoping to get some direction.

    In my VBA project, a worksheet is created, copied to a new book and saved. This worksheet is like an internal user order form and has a few macro embedded shapes on it for use by the user using the form which is emailed to them.

    The macros are stored in the workbook that created the initial worksheet. The users receiving the email with the form in it with the macro embedded shapes do not have access to the original creation workbook, so the macros embedded on the attachment they receive are not executable.

    How can I send out that document with the macros available to the user? (I know this is can be an unsafe practice from the recipient standpoint, but no harm is intended with these macros.)

    My email distribution code is below ...

    Sub Mail_workbook_Outlook_3()
        'Working in Excel 2000-2016
        'Mail a changed copy of the ActiveWorkbook with another file name
        'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
        
        Dim wb1 As Workbook
        Dim wb2 As Workbook
        Dim TempFilePath As String
        Dim TempFileName As String
        Dim FileExtStr As String
        Dim OutApp As Object
        Dim OutMail As Object
        Dim Shp As Shape
    
        With Application
            .ScreenUpdating = False
            .EnableEvents = False
        End With
    
        'Make a copy of the file/Open it/Edit it/Mail it/Delete it
    
        TempFilePath = Environ$("temp") & "\"
        FileExtStr = "." & LCase(Right(wb_tsrf.Name, Len(wb_tsrf.Name) - InStrRev(wb_tsrf.Name, ".", , 1)))
        fnlen = Len(wb_tsrf.Name)
        fnlen = fnlen - 5
        fn = Left(wb_tsrf.Name, fnlen)
        sn = Worksheets(1).Name
        
        TempFileName = fn & "SR"
        
        wb_tsrf.SaveCopyAs TempFilePath & TempFileName & FileExtStr
        Set wb2 = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)
    
    
        '**************Add code to edit the file here********************
    
        With wb2.Worksheets(1)
            .Unprotect
            For Each Shp In ActiveSheet.Shapes
                'MsgBox Shp.Name
                If Shp.Name = "Group 12" Then
                    Shp.Delete
                ElseIf Shp.Name = "Group 3" Then
                    Shp.Delete
                End If
            Next Shp
            .Protect
            Set wb_tar = Workbooks(TempFileName & ".xlsx")
            Debug.Print wb_tar.Name
            CopyModule    
        End With
        
        'Save the file after we changed it with the code above
        'wb2.Save
        wb2.SaveAs TempFilePath & TempFileName & ".xlsm"
    
        Set OutApp = CreateObject("Outlook.Application")
        Set OutMail = OutApp.CreateItem(0)
    
        On Error Resume Next
        With OutMail
            .to = "recipient@email.ca"
            .CC = ""
            .BCC = ""
            .Subject = "### ##### ## SRF (" & sn & ")"
            .Body = "The embedded macros are safe. Choosing to not enable them will not affect the document."
            .Attachments.Add wb2.FullName
            .Send   'or use .Display
        End With
        On Error GoTo 0
        wb2.Close savechanges:=False
    
        'Delete the file
        Kill TempFilePath & TempFileName & FileExtStr
    
        Set OutMail = Nothing
        Set OutApp = Nothing
    
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
        End With
        MsgBox "Message has been sent."
        Stop
    End Sub
    On further research, I found that what I simply (really? simply??) need to do is import the module holding the macros for the buttons from the master workbook to the target. The code in the macros is not written with any public variables or direct references to specific source worksheets etc. (all references are to activesheet or activeworkbook in the macros).

    Here is the code (thanks to ExcelTips)to copy the module (which doesn't seem to be working)

    Sub CopyModule() '(SourceWB As Workbook, strModuleName As String, _
        TargetWB As Workbook)
    
    Dim strFolder As String, strTempFile As String
        strFolder = wb_mat.Path 'source workbook
        strModuleName = "Module4.bas"
        If Len(strFolder) = 0 Then strFolder = CurDir
        strFolder = strFolder & "\"
        strTempFile = strFolder & "Module4.bas"
        On Error Resume Next
        wb_mat.VBProject.VBComponents(strModuleName).Export strTempFile
        wb_tar.VBProject.VBComponents.Import strTempFile
        Kill strTempFile
        On Error GoTo 0
    End Sub
    Questions ....

    1) Can anyone provide a solution as to why the exporting of the module isn't happening? There are no errors, it just doesn't happen.
    2) The line is giving me an error ("Method 'SaveAs' of object '_Workbook' failed.") . It's trying the save the workbook with the newly imported module as an .xlsm file (which I believe if you have macros has to be saved as). I'm assuming it's failing because there are no macros associated with that workbook since the import failed. If issue #1 is taken care of, will that eliminate this error? Or will I still have this error? What could I do then?

    Thank you in advance for your consideration!

  2. #2
    Forum Expert Logit's Avatar
    Join Date
    12-23-2012
    Location
    North Carolina
    MS-Off Ver
    Excel 2019 Professional Plus - 2007 Enterprise
    Posts
    7,438

    Re: Copying VBA Modules Between Workbooks

    .
    One thing that will assist in troubleshooting any macro is to comment out (or delete entirely) the line "On Error Resume Next".

    I did not review the email code for accuracy but I am presuming if you got it from Ron deBruin's site it is good. He does have an
    example of making a copy of the existing workbook and attaching it to the email for sending.

  3. #3
    Forum Guru Andy Pope's Avatar
    Join Date
    05-10-2004
    Location
    Essex, UK
    MS-Off Ver
    O365
    Posts
    20,482

    Re: Copying VBA Modules Between Workbooks

    Perhaps an easier way is to put your code in the sheet object. That way the code will travel with the sheet copy.

    You will only then need to update the OnAction reference of the button(s)
    Cheers
    Andy
    www.andypope.info

  4. #4
    Forum Contributor
    Join Date
    06-15-2009
    Location
    Ontario, canada
    MS-Off Ver
    Office 365
    Posts
    371

    Re: Copying VBA Modules Between Workbooks

    Hi! Thanks so much for stepping in to offer assistance!

    Logit ... I commented out the line you pointed out in the CopyModule code. It stopped on this line with the error "Method 'VBProject' of object '_Workbook' failed. This is a new one for me.
    wb_mat.VBProject.VBComponents(strModuleName).Export strTempFile
    Andy, your approach seems simple enough so I gave it a go. I moved the simple lines of code for the shapes into that worksheet's object code. BTW, here is the code for the macro emedded buttons on the worksheet being copied to a new book.
    Sub Group6_Click() 'PRINT
        ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, IgnorePrintAreas:=False
    End Sub
    
    Sub Group9_Click() 'CLOSE
        With ActiveWorkbook
            ActiveSheet.Protect
            .Save
            .Close
        End With
    End Sub
    The CopyModule code is eliminated altogether from the emailing code.

    However, I run into a problems even before this associated with saving the copied workbook initially. The process of copying the worksheet to a new book is initially created in this module. (This creation is not the one that is emailed. The one emailed is the same worksheet but has some button functionality disabled for the recipient). Refer to this code ...

    Private Sub uf2_create_Click()
        Dim f_range As Range
        
        ...
            
        m1 = Application.WorksheetFunction.Match(uf2_srf.uf2cb_worange.Value, ws_sheet2.Range("O2:O21"), 0)
        rng_low = Application.WorksheetFunction.Index(ws_sheet2.Range("K2:O21"), m1, 1)
        rng_hi = Application.WorksheetFunction.Index(ws_sheet2.Range("K2:O21"), m1, 2)
        sname = Format(rng_low, "ddmmmyy") & "-" & Format(rng_hi, "ddmmmyy")
        
        Application.ScreenUpdating = False
        With ws_srf
            .Visible = True
            .Copy
            .Visible = False
        End With
        Application.ScreenUpdating = True
        ActiveSheet.Name = sname
        Set ws_tsrf = Worksheets(sname)
        
        With ws_tsrf
            .Unprotect
            sname = "SRF_WP_" & sname & ".xlsx"
            fname = "H:\Materials Tracking\Reports\" & sname
            ui1 = InputBox("Please enter user's initials:", vbInformation, "REQUIRED INFORMATION")
            .Range("AB1") = uf2_srf.uf2cb_worange.Value
            .Range("B32") = "   substance (" & un1 & ")"
            
            tr = 8
            nr = 0
            For i = 51 To 72
                If ws_sheet2.Cells(i, 3) > 0 Then
                    .Cells(tr - 1, 1) = "90000"
                    .Cells(tr - 1, 3) = "Salt"
                    .Cells(tr - 1, 2) = ws_sheet2.Cells(i, 3)
                    .Cells(tr - 1, 4) = ui1
                    wo = ws_sheet2.Cells(i, 2)
                        .Cells(tr, 11) = Right(wo, 1)
                        .Cells(tr, 10) = Mid(wo, 5, 1)
                        .Cells(tr, 9) = Mid(wo, 4, 1)
                        .Cells(tr, 8) = Mid(wo, 3, 1)
                        .Cells(tr, 7) = Mid(wo, 2, 1)
                        .Cells(tr, 6) = Left(wo, 1)
                    nr = nr + 1 'change to 1
                    If nr = 12 Then 'add page
                        .Rows("1:33").Copy .Range("34:34")
                        .Range("A41:AN64") = ""
                        tr = 41
                    Else
                        tr = tr + 2
                    End If
                End If
            Next i
            .Protect
            
            MsgBox "New report visible behind this window.", vbExclamation, "REPORT COMPLETED"
            uf2_srf.uf2_create.Enabled = False
            .SaveAs Filename:=fname
            Set wb_tsrf = Workbooks(sname)
            
        End With
        
    End Sub
    This code breaks at the line in red when it tries to save. Since the new workbook has vb associuated to it (in the worksheet object) it will not allow it to save with that (.xlsx) extension.
    If I change the extension to ".xlsm" in the line in blue ... I get "This extension can not be used with the selected file type. Change the file extension in the File name text box or select a different file type by changing the Save as type." as in breaks at the same line as above in red. It doesn't appear as though I can save the newly created workbook with the vba in the sheet.

  5. #5
    Forum Contributor
    Join Date
    06-15-2009
    Location
    Ontario, canada
    MS-Off Ver
    Office 365
    Posts
    371

    Re: Copying VBA Modules Between Workbooks

    It would appear that I have managed to overcomne the file extension related hurdle after a decent Google search.

    I added the argument " FileFormat:=XlFileFormat.xlOpenXMLWorkbookMacroEnabled " which seems to have done the trick.

  6. #6
    Forum Expert Logit's Avatar
    Join Date
    12-23-2012
    Location
    North Carolina
    MS-Off Ver
    Excel 2019 Professional Plus - 2007 Enterprise
    Posts
    7,438

    Re: Copying VBA Modules Between Workbooks

    Jenn68

    Great ! You have it working for you. Good feeling .. huh ?

    What was the solution to : with the error "Method 'VBProject' of object '_Workbook' failed.

  7. #7
    Forum Contributor
    Join Date
    06-15-2009
    Location
    Ontario, canada
    MS-Off Ver
    Office 365
    Posts
    371

    Re: Copying VBA Modules Between Workbooks

    Hi again folks ...
    So I thought I had things good to go. My worksheet (with code attached to the sheet object for the two macro enabled shapes on it) was copied to a new workbook and saved successfully as a .xlsm file. It gets sent off to the recipient.
    The recipient opens the file and enables macros as prompted. However, when they click on the macro enabled button, they get the message "Cannot run the macro ''SRF_WP_07Jan19-13Jan19.xlsm'!SRF_Group6_Click'. The macro may not be available in this workbook or all macros may be disabled."

    The workbook name matches, the only worksheet in the workbook is "SRF" There are two macro enabled shapes available to the user upon receipt of the workbook.

    Sub Group6_Click() 'PRINT
        ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, IgnorePrintAreas:=False
    End Sub
    
    Sub Group9_Click() 'CLOSE
        With ActiveWorkbook
            ActiveSheet.Protect
            .Save
            .Close
        End With
    End Sub
    I do not have the same issue with the "Sub Group9_Click" macro.

    Any thoughts?

  8. #8
    Forum Guru Andy Pope's Avatar
    Join Date
    05-10-2004
    Location
    Essex, UK
    MS-Off Ver
    O365
    Posts
    20,482

    Re: Copying VBA Modules Between Workbooks

    Check the settings for the button that is working, does it match the style of Group6 shape?

    I doubt excel will unravel the sheet name in that format.

  9. #9
    Forum Contributor
    Join Date
    06-15-2009
    Location
    Ontario, canada
    MS-Off Ver
    Office 365
    Posts
    371

    Re: Copying VBA Modules Between Workbooks

    Hi Andy. Your suggestion has revealed that I get the same error on the original.
    I should have checked there first as it was easy then to dsicover the problem

    Thanks for the hint!

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. [SOLVED] Help to combine two Modules from seperate workbooks to one workbook preform task
    By tcrjmom in forum Excel Programming / VBA / Macros
    Replies: 7
    Last Post: 09-30-2014, 06:14 PM
  2. Declaring workbooks for different modules
    By Borg in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 03-22-2012, 09:33 PM
  3. Exporting/Importing modules between two workbooks
    By AnnieLilly in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 08-22-2007, 09:08 PM
  4. Importing Modules From Other Workbooks
    By Jim Jackson in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 07-14-2006, 03:00 PM
  5. Copying modules from Word to Excel
    By Pflugs in forum Excel Programming / VBA / Macros
    Replies: 0
    Last Post: 06-05-2006, 01:35 PM
  6. Copying UserForms & Modules to another workbook
    By excelnut1954 in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 05-24-2006, 05:25 PM
  7. [SOLVED] Extracting (copying) modules from one workbook to another.
    By Devin Linnington in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 07-06-2005, 07:05 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1