Mailmerge from Excel to premade template in Word











up vote
3
down vote

favorite












I've written the following code to take data from the Excel file "Data" and use it for a mailmerge in a prepare Word template named "Template." I'm new to using VBA in word or Access, so any feedback in these areas is very welcome



Sub AccessTransfer()

Dim strPath As String
Dim objAccess As Access.Application
Dim strExcelPath As String
Dim lastRow As Long
lastRow = Sheets("Data").Cells(Rows.Count, 1).End(xlUp).row
Dim rng As Range
Set rng = Sheets("Data").Range("A" & lastRow, "M" & lastRow)
strPath = "L:...MailMergeTEMPDB.accdb"
Set objAccess = CreateObject("Access.Application")
Call objAccess.NewCurrentDatabase(strPath)
objAccess.Visible = False
strExcelPath = Application.ActiveWorkbook.FullName
Set objAccess = New Access.Application
Call objAccess.OpenCurrentDatabase(strPath, False)
objAccess.Visible = False
Call objAccess.DoCmd.TransferSpreadsheet(acImport, _
acSpreadsheetTypeExcel8, "MailMergeTable", strExcelPath, _
True, Range:="Data!")
Access.Application.CloseCurrentDatabase

Dim wdApp As Object, newDoc As Object
Dim strFile As String
strFile = "L:...Template.docm"
Set wdApp = CreateObject("Word.Application")
wdApp.Documents.Open strFile, ReadOnly:=False
wdApp.Visible = True
wdApp.Run "Project.Module1.WordMailMerge"
Kill "L:....MailMergeTEMPDB.accdb"
End Sub


And then Macro called from within Word is:



Sub WordMailMerge()
Dim strFile As String
strFile = "L:...MailMergeTEMPDB.accdb"
ActiveDocument.MailMerge.OpenDataSource Name:= _
strFile _
, ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _
AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:="", _
WritePasswordDocument:="", WritePasswordTemplate:="", Revert:=False, _
Format:=wdOpenFormatAuto, Connection:= _
"Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=strFile;Mode=Read;Extended Properties="""";Jet OLEDB:System database="""";Jet OLEDB:Registry Path=""""" _
, SQLStatement:="SELECT * FROM `MailMergeTable`", SQLStatement1:="", _
SubType:=wdMergeSubTypeAccess
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
Windows("AH_MacroMailMergeTemplate").Activate
ActiveDocument.Close
End Sub


I'm also new to using VBA to navigate trough directories, so feedback in this aspect would be appreciated too.










share|improve this question
























  • Apologies. I left out an "End Sub"
    – user1996971
    Jun 14 '16 at 15:10






  • 2




    Why do you transfer data from Access database to Excel? You can create Word MailMerge object directly from that database. See this MSDN documentation
    – Maciej Los
    Jun 15 '16 at 16:34












  • Hmm. I did not know that. This changes everything. Thank you.
    – user1996971
    Jun 16 '16 at 10:55















up vote
3
down vote

favorite












I've written the following code to take data from the Excel file "Data" and use it for a mailmerge in a prepare Word template named "Template." I'm new to using VBA in word or Access, so any feedback in these areas is very welcome



Sub AccessTransfer()

Dim strPath As String
Dim objAccess As Access.Application
Dim strExcelPath As String
Dim lastRow As Long
lastRow = Sheets("Data").Cells(Rows.Count, 1).End(xlUp).row
Dim rng As Range
Set rng = Sheets("Data").Range("A" & lastRow, "M" & lastRow)
strPath = "L:...MailMergeTEMPDB.accdb"
Set objAccess = CreateObject("Access.Application")
Call objAccess.NewCurrentDatabase(strPath)
objAccess.Visible = False
strExcelPath = Application.ActiveWorkbook.FullName
Set objAccess = New Access.Application
Call objAccess.OpenCurrentDatabase(strPath, False)
objAccess.Visible = False
Call objAccess.DoCmd.TransferSpreadsheet(acImport, _
acSpreadsheetTypeExcel8, "MailMergeTable", strExcelPath, _
True, Range:="Data!")
Access.Application.CloseCurrentDatabase

Dim wdApp As Object, newDoc As Object
Dim strFile As String
strFile = "L:...Template.docm"
Set wdApp = CreateObject("Word.Application")
wdApp.Documents.Open strFile, ReadOnly:=False
wdApp.Visible = True
wdApp.Run "Project.Module1.WordMailMerge"
Kill "L:....MailMergeTEMPDB.accdb"
End Sub


And then Macro called from within Word is:



Sub WordMailMerge()
Dim strFile As String
strFile = "L:...MailMergeTEMPDB.accdb"
ActiveDocument.MailMerge.OpenDataSource Name:= _
strFile _
, ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _
AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:="", _
WritePasswordDocument:="", WritePasswordTemplate:="", Revert:=False, _
Format:=wdOpenFormatAuto, Connection:= _
"Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=strFile;Mode=Read;Extended Properties="""";Jet OLEDB:System database="""";Jet OLEDB:Registry Path=""""" _
, SQLStatement:="SELECT * FROM `MailMergeTable`", SQLStatement1:="", _
SubType:=wdMergeSubTypeAccess
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
Windows("AH_MacroMailMergeTemplate").Activate
ActiveDocument.Close
End Sub


I'm also new to using VBA to navigate trough directories, so feedback in this aspect would be appreciated too.










share|improve this question
























  • Apologies. I left out an "End Sub"
    – user1996971
    Jun 14 '16 at 15:10






  • 2




    Why do you transfer data from Access database to Excel? You can create Word MailMerge object directly from that database. See this MSDN documentation
    – Maciej Los
    Jun 15 '16 at 16:34












  • Hmm. I did not know that. This changes everything. Thank you.
    – user1996971
    Jun 16 '16 at 10:55













up vote
3
down vote

favorite









up vote
3
down vote

favorite











I've written the following code to take data from the Excel file "Data" and use it for a mailmerge in a prepare Word template named "Template." I'm new to using VBA in word or Access, so any feedback in these areas is very welcome



Sub AccessTransfer()

Dim strPath As String
Dim objAccess As Access.Application
Dim strExcelPath As String
Dim lastRow As Long
lastRow = Sheets("Data").Cells(Rows.Count, 1).End(xlUp).row
Dim rng As Range
Set rng = Sheets("Data").Range("A" & lastRow, "M" & lastRow)
strPath = "L:...MailMergeTEMPDB.accdb"
Set objAccess = CreateObject("Access.Application")
Call objAccess.NewCurrentDatabase(strPath)
objAccess.Visible = False
strExcelPath = Application.ActiveWorkbook.FullName
Set objAccess = New Access.Application
Call objAccess.OpenCurrentDatabase(strPath, False)
objAccess.Visible = False
Call objAccess.DoCmd.TransferSpreadsheet(acImport, _
acSpreadsheetTypeExcel8, "MailMergeTable", strExcelPath, _
True, Range:="Data!")
Access.Application.CloseCurrentDatabase

Dim wdApp As Object, newDoc As Object
Dim strFile As String
strFile = "L:...Template.docm"
Set wdApp = CreateObject("Word.Application")
wdApp.Documents.Open strFile, ReadOnly:=False
wdApp.Visible = True
wdApp.Run "Project.Module1.WordMailMerge"
Kill "L:....MailMergeTEMPDB.accdb"
End Sub


And then Macro called from within Word is:



Sub WordMailMerge()
Dim strFile As String
strFile = "L:...MailMergeTEMPDB.accdb"
ActiveDocument.MailMerge.OpenDataSource Name:= _
strFile _
, ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _
AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:="", _
WritePasswordDocument:="", WritePasswordTemplate:="", Revert:=False, _
Format:=wdOpenFormatAuto, Connection:= _
"Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=strFile;Mode=Read;Extended Properties="""";Jet OLEDB:System database="""";Jet OLEDB:Registry Path=""""" _
, SQLStatement:="SELECT * FROM `MailMergeTable`", SQLStatement1:="", _
SubType:=wdMergeSubTypeAccess
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
Windows("AH_MacroMailMergeTemplate").Activate
ActiveDocument.Close
End Sub


I'm also new to using VBA to navigate trough directories, so feedback in this aspect would be appreciated too.










share|improve this question















I've written the following code to take data from the Excel file "Data" and use it for a mailmerge in a prepare Word template named "Template." I'm new to using VBA in word or Access, so any feedback in these areas is very welcome



Sub AccessTransfer()

Dim strPath As String
Dim objAccess As Access.Application
Dim strExcelPath As String
Dim lastRow As Long
lastRow = Sheets("Data").Cells(Rows.Count, 1).End(xlUp).row
Dim rng As Range
Set rng = Sheets("Data").Range("A" & lastRow, "M" & lastRow)
strPath = "L:...MailMergeTEMPDB.accdb"
Set objAccess = CreateObject("Access.Application")
Call objAccess.NewCurrentDatabase(strPath)
objAccess.Visible = False
strExcelPath = Application.ActiveWorkbook.FullName
Set objAccess = New Access.Application
Call objAccess.OpenCurrentDatabase(strPath, False)
objAccess.Visible = False
Call objAccess.DoCmd.TransferSpreadsheet(acImport, _
acSpreadsheetTypeExcel8, "MailMergeTable", strExcelPath, _
True, Range:="Data!")
Access.Application.CloseCurrentDatabase

Dim wdApp As Object, newDoc As Object
Dim strFile As String
strFile = "L:...Template.docm"
Set wdApp = CreateObject("Word.Application")
wdApp.Documents.Open strFile, ReadOnly:=False
wdApp.Visible = True
wdApp.Run "Project.Module1.WordMailMerge"
Kill "L:....MailMergeTEMPDB.accdb"
End Sub


And then Macro called from within Word is:



Sub WordMailMerge()
Dim strFile As String
strFile = "L:...MailMergeTEMPDB.accdb"
ActiveDocument.MailMerge.OpenDataSource Name:= _
strFile _
, ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _
AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:="", _
WritePasswordDocument:="", WritePasswordTemplate:="", Revert:=False, _
Format:=wdOpenFormatAuto, Connection:= _
"Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=strFile;Mode=Read;Extended Properties="""";Jet OLEDB:System database="""";Jet OLEDB:Registry Path=""""" _
, SQLStatement:="SELECT * FROM `MailMergeTable`", SQLStatement1:="", _
SubType:=wdMergeSubTypeAccess
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
Windows("AH_MacroMailMergeTemplate").Activate
ActiveDocument.Close
End Sub


I'm also new to using VBA to navigate trough directories, so feedback in this aspect would be appreciated too.







vba excel






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 14 '16 at 15:10

























asked Jun 14 '16 at 15:00









user1996971

25817




25817












  • Apologies. I left out an "End Sub"
    – user1996971
    Jun 14 '16 at 15:10






  • 2




    Why do you transfer data from Access database to Excel? You can create Word MailMerge object directly from that database. See this MSDN documentation
    – Maciej Los
    Jun 15 '16 at 16:34












  • Hmm. I did not know that. This changes everything. Thank you.
    – user1996971
    Jun 16 '16 at 10:55


















  • Apologies. I left out an "End Sub"
    – user1996971
    Jun 14 '16 at 15:10






  • 2




    Why do you transfer data from Access database to Excel? You can create Word MailMerge object directly from that database. See this MSDN documentation
    – Maciej Los
    Jun 15 '16 at 16:34












  • Hmm. I did not know that. This changes everything. Thank you.
    – user1996971
    Jun 16 '16 at 10:55
















Apologies. I left out an "End Sub"
– user1996971
Jun 14 '16 at 15:10




Apologies. I left out an "End Sub"
– user1996971
Jun 14 '16 at 15:10




2




2




Why do you transfer data from Access database to Excel? You can create Word MailMerge object directly from that database. See this MSDN documentation
– Maciej Los
Jun 15 '16 at 16:34






Why do you transfer data from Access database to Excel? You can create Word MailMerge object directly from that database. See this MSDN documentation
– Maciej Los
Jun 15 '16 at 16:34














Hmm. I did not know that. This changes everything. Thank you.
– user1996971
Jun 16 '16 at 10:55




Hmm. I did not know that. This changes everything. Thank you.
– user1996971
Jun 16 '16 at 10:55










1 Answer
1






active

oldest

votes

















up vote
0
down vote













There's no need to Call anything, it's obsolete. Instead just use Sub argument, argument.



What's this




Kill "L:....MailMergeTEMPDB.accdb"



Is this closing the access object? Is this deleting the file? Be explicit - Kill isn't something you generally want to see in any code.



FSO.Deletefile strPath





share|improve this answer





















    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    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: "196"
    };
    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',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    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%2fcodereview.stackexchange.com%2fquestions%2f131979%2fmailmerge-from-excel-to-premade-template-in-word%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    There's no need to Call anything, it's obsolete. Instead just use Sub argument, argument.



    What's this




    Kill "L:....MailMergeTEMPDB.accdb"



    Is this closing the access object? Is this deleting the file? Be explicit - Kill isn't something you generally want to see in any code.



    FSO.Deletefile strPath





    share|improve this answer

























      up vote
      0
      down vote













      There's no need to Call anything, it's obsolete. Instead just use Sub argument, argument.



      What's this




      Kill "L:....MailMergeTEMPDB.accdb"



      Is this closing the access object? Is this deleting the file? Be explicit - Kill isn't something you generally want to see in any code.



      FSO.Deletefile strPath





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        There's no need to Call anything, it's obsolete. Instead just use Sub argument, argument.



        What's this




        Kill "L:....MailMergeTEMPDB.accdb"



        Is this closing the access object? Is this deleting the file? Be explicit - Kill isn't something you generally want to see in any code.



        FSO.Deletefile strPath





        share|improve this answer












        There's no need to Call anything, it's obsolete. Instead just use Sub argument, argument.



        What's this




        Kill "L:....MailMergeTEMPDB.accdb"



        Is this closing the access object? Is this deleting the file? Be explicit - Kill isn't something you generally want to see in any code.



        FSO.Deletefile strPath






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 20 at 9:13









        Raystafarian

        5,7841047




        5,7841047






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f131979%2fmailmerge-from-excel-to-premade-template-in-word%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

            Morgemoulin

            Scott Moir

            Souastre