Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Error when running macro that merges and saves MSWord docs as PDFs

Posted on 2013-06-06
4
Medium Priority
?
523 Views
Last Modified: 2013-06-11
Hi Experts

I've found some very useful macro code which helps me to automatically merge and save individual PDFs documents.

I've associated the macro with a button in a MSWord document. It automatically opens my MSWord document (which is a certificate) that contains merge fields linking it to a MSAccess query and then creates individucal MSWord documents for each records and finally PDFs them in the same process.

Everything works as I would except it to and all PDFs get created, however I'm receiving this error at the end of the process, "This file is in use by another application or user."

Can anyone help with with why this happens? I have attached a text document with the code.

Thanks in advance
darls15
MergePDFsCode.txt
0
Comment
Question by:darls15
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 76

Expert Comment

by:GrahamSkan
ID: 39228588
I can't quarrel with the first macro. I recognise one of my own comments in it.

However the second one tries to open every file in the folder and create a PDF from it, even if it is already a PDF. The rename from .doc to .pdf won't do anything, so you will be trying to export to a file that is already open. This version filters out the files that aren't Word documents.
Sub ConvertWordsToPdfs()

    Dim strFolder As String
    Dim strFile As String
    Dim doc As Document
    Dim newName As String
    Dim strNameParts() As String
    
    
    strFolder = "G:\General\OUTPUT"
    strFile = Dir(strFolder & "\*.doc*") ' word document files only (.doc, .docx, .docm)
    Do Until strFile = ""
        strNameParts = Split(strFile, ".")
        strNameParts(UBound(strNameParts)) = "pdf" .set extension to pdf
        newName = Join(strNameParts, ".")
        Set doc = Documents.Open(strFolder & "\" & strFile)
        doc.ExportAsFixedFormat OutputFileName:=strFolder & "\" & newName, _
                ExportFormat:=wdExportFormatPDF
        doc.Close wdDoNotSaveChanges
        strFile = Dir
    Loop

End Sub

Open in new window

If you don't need to have Word document copies you can export in the first macro:
Sub MergeToPDFs()
    Dim wdMainDoc As Word.Document
    Dim r As Integer
    Dim rng As Word.Range
    Dim wdResultDoc As Document
    
    Set wdMainDoc = Documents.Open("G:\General\Certificates.docm")
    With wdMainDoc.MailMerge
        .MainDocumentType = wdFormLetters
        .Destination = wdSendToNewDocument
        .SuppressBlankLines = True
        .DataSource.ActiveRecord = wdFirstDataSourceRecord
        Do
            'Do the Mail Merge to new document
            With .DataSource
                .FirstRecord = .ActiveRecord
                .LastRecord = .ActiveRecord
            End With
            'Set the value from the merge data
            .Execute
            'Export the resulting document
            Set wdResultDoc = ActiveDocument
            wdResultDoc.ExportAsFixedFormat _
                OutputFileName:="G:\General\OUTPUT\" & .DataSource.DataFields("RegESW").Value & ".doc", _
                ExportFormat:=wdExportFormatPDF
            wdResultDoc.Close wdDoNotSaveChanges
            r = .DataSource.ActiveRecord
            .DataSource.ActiveRecord = wdNextDataSourceRecord
            'recordcount might not be findable (=-1),
            'so just check to see if we're stuck on the same record
        Loop Until r = .DataSource.ActiveRecord
    End With
    wdMainDoc.Close wdDoNotSaveChanges
End Sub

Open in new window

0
 

Author Comment

by:darls15
ID: 39236631
Hi Graham

First of all, thank you for the original macro, this is going to help me a lot!

I tried your amended ConvertWordsToPdfs macro and it works very well and all PDFs are created without error.

I then tried your second macro as I don't need to keep the copies of the Word documents however it only created the Word versions and stopped.

Can you please help?

Thanks
darls15
0
 
LVL 76

Accepted Solution

by:
GrahamSkan earned 2000 total points
ID: 39236996
I did fail to change the extension for the output file to .pdf. This is now corrected.

Also, for easier maintenance, the three strings that are likely to need changing to suit individual circumstances have been pulled out to be at the start of the procedure.
Sub MergeToPDFs()
    Dim wdMainDoc As Word.Document
    Dim r As Integer
    Dim wdResultDoc As Document
    
    Dim strMainDocument As String
    Dim strOutputFolder As String
    Dim strDataFieldForName As String
    
    strMainDocument = "C:\MyMergeDocs\MMtest.docx"
    strOutputFolder = "C:\PDFFolder\"
    strDataFieldForName = "NameField"
    
    Set wdMainDoc = Documents.Open(strMainDocument)
    With wdMainDoc.MailMerge
        .MainDocumentType = wdFormLetters
        .Destination = wdSendToNewDocument
        .SuppressBlankLines = True
        .DataSource.ActiveRecord = wdFirstDataSourceRecord
        Do
            'Do the Mail Merge to new document
            With .DataSource
                .FirstRecord = .ActiveRecord
                .LastRecord = .ActiveRecord
            End With
            .Execute
            'Export the resulting document
            Set wdResultDoc = ActiveDocument
            wdResultDoc.ExportAsFixedFormat _
                OutputFileName:=strOutputFolder & .DataSource.DataFields(strDataFieldForName).Value & ".pdf", _
                ExportFormat:=wdExportFormatPDF
            wdResultDoc.Close wdDoNotSaveChanges
            r = .DataSource.ActiveRecord
            .DataSource.ActiveRecord = wdNextDataSourceRecord
            'recordcount might not be findable (=-1),
            'so just check to see if we're stuck on the same record
        Loop Until r = .DataSource.ActiveRecord
    End With
    wdMainDoc.Close wdDoNotSaveChanges
End Sub

Open in new window

0
 

Author Closing Comment

by:darls15
ID: 39239452
This is brilliant & works perfectly! Thanks for all your help Graham.

Have a great day.
darls15
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes how to use a set of graphical playing cards to create a Draw Poker game in Excel or VB6.
With its various features, Office 365 can not only help you with your day-to-day business tasks, it can also do wonders for your marketing campaign.
Office 365 is currently available in five editions. Three of them are for business use: Office 365 Business Essentials, Office 365 Business, and Office 365 Business Premium. Two of them are for home/personal use: Office 365 Home and Office 365 Perso…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

610 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question