How to Completely Close Word application using VB script - vba

I have a macro / script in word that converts docx files into PDF; once the files are converted, I want to just simply close the word application (the macro). The conversion part works well, but the macro still remains open. …How would I go about closing the macro / MS word application once all the files are converted?
The script:
Sub BatchConvertDocxToPDF()
Dim objDoc As Document
Dim strFile As String, strFolder As String
'Initialization
strFolder = "C:\Users\Public\ConvertedFiles\"
strFile = Dir(strFolder & "*.docx", vbNormal)
'Precess each file in the file folder and convert them to pdf.
While strFile <> ""
Set objDoc = Documents.Open(FileName:=strFolder & strFile)
objDoc.ExportAsFixedFormat _
OutputFileName:=Replace(objDoc.FullName, ".docx", ".pdf"), _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, Item:=wdExportDocumentContent
objDoc.Close
strFile = Dir()
Wend
'close word
Set AppWord = CreateObject("Word.Application")
AppWord.Visible = True
AppWord.Application.Quit
End Sub
Thank you in advance for any assistance

Simply use
Application.Quit
Instead of
Set AppWord = CreateObject("Word.Application")
AppWord.Visible = True
AppWord.Application.Quit
This bit creates a new instance of Word only to close it immediately, which is completely useless.

Related

How to convert multiple word documents from .doc to .docx?

I have many .doc documents located in many subfolders and I would like to covert them to .docx
I was opening each file and saving it but there are too many of them, so I thought there must be a better and a faster way. I found online some VBA code but none seem to work.
First VBA code:
Sub TranslateDocIntoDocx()
Dim objWordApplication As New Word.Application
Dim objWordDocument As Word.Document
Dim strFile As String
Dim strFolder As String
strFolder = "H:\Vanhuspalvelut\Kotihoito\Tammelan_kotihoito\TURVALLISUUS\Pelastussuunnitelmaan_tuleva\TURVALLISUUS_SUUNNITELMA_2015"
strFile = Dir(strFolder & "*.doc", vbNormal)
While strFile <> ""
With objWordApplication
Set objWordDocument = .Documents.Open(FileName:=strFolder & strFile, AddToRecentFiles:=False, ReadOnly:=True, Visible:=False)
With objWordDocument
.SaveAs FileName:=strFolder & Replace(strFile, "doc", "docx"), FileFormat:=16
.Close
End With
End With
strFile = Dir()
Wend
Set objWordDocument = Nothing
Set objWordApplication = Nothing
End Sub
Second VBA code:
Sub ConvertBatchToDOCX()
Dim sSourcePath As String
Dim sTargetPath As String
Dim sDocName As String
Dim docCurDoc As Document
Dim sNewDocName As String
' Looking in this path
sSourcePath = "H:\Vanhuspalvelut\Kotihoito\Tammelan_kotihoito\TURVALLISUUS\Pelastussuunnitelmaan_tuleva\TURVALLISUUS_SUUNNITELMA_2015"
sTargetPath = "H:\Vanhuspalvelut\Kotihoito\Tammelan_kotihoito\TURVALLISUUS\Pelastussuunnitelmaan_tuleva\TURVALLISUUS_SUUNNITELMA_2015"
' Look for first DOC file
sDocName = Dir(sSourcePath & "*.doc")
Do While sDocName <> ""
' Repeat as long as there are source files
'Only work on files where right-most characters are ".doc"
If Right(sDocName, 4) = ".doc" Then
' Open file
Set docCurDoc = Documents.Open(FileName:=sSourcePath & sDocName)
sNewDocName = Replace(sDocName, ".doc", ".docx")
With docCurDoc
.SaveAs FileName:=sTargetPath & sNewDocName, _
FileFormat:=wdFormatDocumentDefault
.Close SaveChanges:=wdDoNotSaveChanges
End With
End If
' Get next source file name
sDocName = Dir
Loop
MsgBox "Finished"
End Sub
Any help would be much appreciated!
In both routines you have the same small mistake: You miss a Backslash between the path and the filename. Your Dir-Command will see the following command and therefore doesn't find anything:
Dir("H:\Vanhuspalvelut\Kotihoito\Tammelan_kotihoito\TURVALLISUUS\Pelastussuunnitelmaan_tuleva\TURVALLISUUS_SUUNNITELMA_2015*.doc", vbNormal
Either add the backslash at the end of the path definition:
strFolder = "H:\Vanhuspalvelut\Kotihoito\Tammelan_kotihoito\TURVALLISUUS\Pelastussuunnitelmaan_tuleva\TURVALLISUUS_SUUNNITELMA_2015\"
or put it into the Dir-command:
strFile = Dir(strFolder & "\*.doc", vbNormal)

Word Document created does not convert to PDF

Generated Word Document does not convert to PDF
I generate a Word Document populating the bookmarks within it from excel and then tried exporting to PDF. Constantly getting error even after adding Microsoft Word Library 16.0. What am I doing wrong here?
Option Explicit
Sub GenerateTerminationLetter()
Dim objWord As Object, docWord As Object
Dim wb As Workbook
Dim xlName As Name
Dim Path, SavePath, TempPath, FileName3 As String
Dim EmpFileName As String
Set wb = ThisWorkbook
' ******************************* Primary Letter Template Location ***********************
Sheets("FilePath").Select
TempPath = Sheets("FilePath").Range("C16").Value
If Right(TempPath, 1) <> "\" Then
TempPath = TempPath & "\"
Else
End If
Path = TempPath & "Termination Letter (Redundancy A023 FPP) (NEW - With Whistle Blowing Statement).docx"
'*******************************Populate Bookmarks ***************************************
On Error GoTo ErrorHandler
'Create a new Word Session
Set objWord = CreateObject("Word.Application")
'Open document in word
Set docWord = objWord.Documents.Add(Path)
'Loop through names in the activeworkbook
For Each xlName In wb.Names
'if xlName's name exists in the document then put the value at the bookmark
If docWord.Bookmarks.Exists(xlName.Name) Then
docWord.Bookmarks(xlName.Name).Range.Text = Range(xlName.Value)
End If
Next xlName
Sheets("Temp").Visible = xlVeryHidden
'******************************* Activate word and display document **********************
With objWord
.Visible = True
.Activate
End With
'Save Termination Letter
FileName3 = Sheets("R-Copy").Range("D7").Value
'******************************* Export as PDF ********************************************
docWord.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=EmpFolder & "\" & "Termination Letter_" & FileName3, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
ExportFormat:=wdExportFormatPDF
objWord.Quit
'Release the Word object to save memory and exit macro
ErrorExit:
Set objWord = Nothing
Exit Sub
'Error Handling routine
ErrorHandler:
If Err Then
MsgBox "Error No: " & Err.Number & "; There is a problem. Contact Administrator"
If Not objWord Is Nothing Then objWord.Quit False
Resume ErrorExit
End If
End Sub
Error No. 448: Contact Administrator
Which line is triggering the error? I'm assuming its the exportAsFixedFormat line. Error 448 is Named argument not found, and it looks like Type isn't one of the allowed arguments. You problably want ExportFormat:=wdExportFormatPDF, which it looks like you've included, but Type isn't an allowed argument, and will cause an error. Here's the docs on that method: https://learn.microsoft.com/en-us/office/vba/api/word.document.exportasfixedformat
It looks like some of the other arguments you're using aren't quite right, too, since they're referencing xl instead of wd types and the property names don't quite line up. Try:
docWord.ExportAsFixedFormat _
OutputFileName:=EmpFolder & "\" & "Termination Letter_" & FileName3, _
IncludeDocProps:=True, _
ExportFormat:=wdExportFormatPDF
Also, I don't believe you are setting EmpFolder anywhere, so it's an empty variable, which is probably either going to make the method fail or cause it to save the file in the wrong place.
Let me know if that works for you.
Sub BatchConvertDocxToPDF()
Dim objDoc1, objWord1 As Object
Dim strFile As String, strFolder, fp As String
'Initialization
strFolder = EmpFolder & "\"
strFile = Dir(strFolder & "*.docx", vbNormal)
xp = strFolder & strFile
'Process each file in the file folder and convert them to pdf.
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
While strFile <> ""
Set objDoc1 = objWord.Documents.Open(Filename:=strFolder & strFile)
objDoc1.ExportAsFixedFormat _
OutputFileName:=Replace(objDoc1.FullName, ".docx", ".pdf"), _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False,
OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, Item:=wdExportDocumentContent
objDoc1.Close
strFile = Dir()
Wend
objWord.Visible = False
Set objDoc1 = Nothing
Set objWord = Nothing
End Sub

Why are my MergeField names the only data pulling through to a PDF via MailMerge in Excel?

I am currently trying to use the code below in VBA to bring data in a table into a mailmerge word document which then saves the individual merges as a pdf. The code almost does this but when I run the macro on my excel sheet the pdf's saved only bring through the mergefield names from the word document and not the data itself.
Any ideas on where I can go from here? I am currently using Office 2016.
Sub RunMailMerge()
Dim objWord
Dim objDoc
Dim StrFolder As String, StrName As String, i As Long, j As Long
Dim strWorkbookName As String: strWorkbookName = ThisWorkbook.FullName
Const StrNoChr As String = """*./\:?|": StrName = "Easy.docx"
StrFolder = ThisWorkbook.Path & Application.PathSeparator
If Dir(StrFolder & strDocNm) = "" Then Exit Sub
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
With objWord
'Disable alerts to prevent an SQL prompt
.DisplayAlerts = wdAlertsNone
'Display Word - change this to False once the code is running correctly
.Visible = False
'Open the mailmerge main document - set Visible:=True for testing
Set objWord = .Documents.Open(Filename:=StrFolder & StrName, ReadOnly:=True,
AddToRecentFiles:=False, Visible:=False)
With objWord
With .MailMerge
'Define the mailmerge type
.MainDocumentType = wdFormLetters
'Define the output
.Destination = wdSendToNewDocument
.SuppressBlankLines = False
'Connect to the data source
.OpenDataSource Name:=strWorkbookName, _
ReadOnly:=True, _
LinkToSource:=False, _
AddToRecentFiles:=False, _
Format:=wdOpenFormatAuto, _
Connection:="User ID=Admin;DataSource=strWorkbookName;" & _
"Mode=Read;Extended Properties=""HDR=YES;IMEX=1"";", _
SQLStatement:="SELECT * FROM `Sheet1 SQLStatement:=", _
SubType:=wdMergeSubTypeAccess
'Process all eligible records
For i = 1 To .DataSource.RecordCount
With .DataSource
.FirstRecord = i
.LastRecord = i
.ActiveRecord = i
'Exit if the field to be used for the filename is empty
If Trim(.DataFields("Tenant")) = "" Then Exit For
'StrFolder = .DataFields("Folder") & Application.PathSeparator
StrName = .DataFields("Tenant")
End With
.Execute Pause:=True
'Clean up the filename
For j = 1 To Len(StrNoChr)
StrName = Replace(StrName, Mid(StrNoChr, j, 1), "_")
Next
StrName = "Letter - " & Trim(StrName)
'Save as a PDF
objWord.SaveAs Filename:=StrFolder & StrName & ".pdf", _
FileFormat:=wdFormatPDF, AddToRecentFiles:=False
Next i
'Disconnect from the data source
.MainDocumentType = wdNotAMergeDocument
End With
'Close the mailmerge main document
.Close False
End With
Call CloseAll
Set wdDoc = Nothing: Set wdApp = Nothing
End With
End Sub
Sub CloseAll()
Dim objWord
Dim objDoc
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
objWord.ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
End Sub
That code is essentially a copy of code I've posted elsewhere (e.g. https://www.mrexcel.com/forum/general-excel-discussion-other-questions/713478-word-2007-2010-mail-merge-save-individual-pdf-files-post4796480.html#post4796480), but why you'd add your call to CloseAll is a mystery.
Nonetheless, it's also clear you've also partially modified the code for use with late binding, by replacing:
Dim wdApp As New Word.Application, wdDoc As Word.Document
with:
Dim objWord
Dim objDoc
...
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
Had you stuck with early binding throughout, the code would work. Right now, though, your modified code employs a mix of late binding with named Word constants, which are really only applicable to early binding. You need to fully adapt the code to late binding or revert to code that is entirely early binding.
Why are you trying to drive a mail merge via VBA code? You should be able to A) set up the data in Excel or Access, B) set up the template in Word & connect it to the data source, C) run the mail merge. Unless you're doing something really, really fancy, there should be no need for VBA.
Since it seems some sadist has forced you to do things the hard way, it looks like your error is most likely here:
Connection:="User ID=Admin;DataSource=strWorkbookName;" & _
"Mode=Read;Extended Properties=""HDR=YES;IMEX=1"";", _
SQLStatement:="SELECT * FROM `Sheet1
SQLStatement:=", _
SubType:=wdMergeSubTypeAccess
First of all:
Connection:="User ID=Admin;DataSource=strWorkbookName;" & _
should be
Connection:="User ID=Admin;DataSource=" & strWorkbookName & ";" & _
Second, your SQLStatement parameter is unterminated, and I'm pretty sure that "Sheet1" (not sure why you have an extra backtick in there) isn't the way to reference the "table" (i.e. worksheet) when selecting from an Excel workbook. IIRC, it should be "WorkBook$WorkSheet", so this:
SQLStatement:="SELECT * FROM `Sheet1
should be something like:
SQLStatement:="SELECT * FROM " & strWorkbookName & "$Sheet1", _
That line is followed by the end of the string
SQLStatement:=", _
which was part of the actual SQL string being sent to the database engine in Excel. That ain't gonna work.
The way I read it, that line should be:
Connection:="User ID=Admin;DataSource=" & strWorkbookName & ";" & _
"Mode=Read;Extended Properties=""HDR=YES;IMEX=1"";", _
SQLStatement:="SELECT * FROM " & strWorkbookName & "$Sheet1", _
SubType:=wdMergeSubTypeAccess
You may have to tweak it a bit, but I think that'll get you on the right track.

Open and save Word doc with Excel VBA doesn't work

I would like to open a Word doc, paste data from my Excel file and then save that Word document.
Opening Word and pasting the data works fine, but it doesn't save the file due to a problem with the line "ChDir "C:\My Documents\".
What am I missing here?
Sub macro()
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
WordApp.Activate
Set WordDoc = WordApp.Documents.Add
Range("A1:C33").Copy
WordApp.Selection.PasteSpecial Link:=False, DataType:=wdPasteRTF, _Placement:=wdInLine, DisplayAsIcon:=False
WordDoc.PageSetup.LeftMargin = CentimetersToPoints(1.5)
WordDoc.PageSetup.TopMargin = CentimetersToPoints(1.4)
WordDoc.PageSetup.BottomMargin = CentimetersToPoints(1.5)
ChDir "C:\My Documents\Test"
ActiveDocument.SaveAs "Archief" & Format(Now, "yyyymmdd") & ".docx"
Set WordDoc = Nothing
Set WordApp = Nothing
End Sub
It would be easier to create a variable to include both the path and the name of the file, like this :
Dim FileFullName As String
FileFullName = Environ("userprofile") & "\My Documents\Test" & "\" & "Archief" & Format(Now, "yyyymmdd") & ".docx"
ActiveDocument.SaveAs FileFullName
Try this:
Dim FileName2 As String
Set appWrd = CreateObject("Word.Application")
appWrd.DisplayAlerts = False
FileName2 = Document.Path & "\" & ".docx"
appWrd.ActiveDocument.SaveAs FileName:=FileName2

VBA script convert folder of .rtf files to .docx files - two minor problems

I use a VBA script (see below) in Word 2013 to convert a folder of .rtf files to .docx files. It mostly works, but has two minor problems.
I have to acknowledge that each original file is an .rtf file. When Word opens each .rtf file there's a dialog that requires me to confirm that each file is an .rtf file.
When I view converted .docx files in Word there's a "compatibility mode" header, which suggests that I haven't properly converted.
Are there any fixes for these problems? The first one kind of undermines the whole point of scripting and I'm afraid the second one will cause unforeseen problems.
Sub ConvertRtfToDocx()
Set oWord = CreateObject("Word.Application")
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select folder..."
.Show
myFolder = .SelectedItems.Item(1)
End With
myWildCard = InputBox(prompt:="Enter wild card...")
myDocs = Dir(myFolder & "\" & myWildCard)
While myDocs <> ""
Debug.Print myDocs
Set oDoc = oWord.Documents.Open(myFolder & "\" & myDocs)
oDoc.SaveAs myFolder & "\" & Left(myDocs, Len(myDocs) - 4) & ".docx", _
wdFormatXMLDocument
myDocs = Dir()
Wend
oWord.Quit
End Sub
The following code works.
Sub ConvertRtfToDocx()
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select folder..."
.Show
myFolder = .SelectedItems.Item(1)
End With
myWildCard = InputBox(prompt:="Enter wild card...")
myDocs = Dir(myFolder & "\" & myWildCard)
While myDocs <> ""
Documents.Open FileName:=myFolder & "\" & myDocs, ConfirmConversions:=False
ActiveDocument.SaveAs2 FileName:=myFolder & "\" & Left(myDocs, Len(myDocs) - 4) & ".docx", _
FileFormat:=wdFormatDocumentDefault, _
CompatibilityMode:=wdCurrent
ActiveDocument.Close SaveChanges:=False
myDocs = Dir()
Wend
End Sub
I did some restructuring (e.g., use ActiveDocument instead of creating my own object), but the real changes that did it were to
set ConfirmConversions:=False on open
use the SaveAs2 method and set FileFormat:=wdFormatDocumentDefault and CompatibilityMode:=wdCurrent
I guess that both of these can be set as default (I'm overwhelmed by Office options and leave the defaults).