Check if Word Document is already opened + Error Handling - excel

Hello and thank you for your answers in advance.
I am opening a word document using excel-vba and save it under a new name.
This is actually working fine.
But problems occur if the word document with the new name is already opened!
Let's say there is a button to run the script and the user runs it the second time, and has the created file still opened. The user might change something in excel and now wants to check how the new word document would look like afterwords. He will click the button again.
It will open the template (do all changes) and try to save it, but can't because it is already opened and it might save this document with the old name (template) instead of a new file. Therefor it will overwrite and destroy the template file (got this several times during testing)!
Therefore I am in need of some proper code and a better Error-Handling. My first thought is to check if the document with the filename already exists. But it does not quite do its job:
Sub CreateWordDocument()
Dim TemplName, CurrentLocation, DocumentName, Document As String
Dim WordDoc, WordApp, OutApp As Object
With table1
TemplName = table1.Range("A1").Value 'Get selected template name
CurrentLocation = Application.ActiveWorkbook.Path 'working folder
Template = CurrentLocation + "\" + TemplName
DocumentName = .Range("A2").Value
Document = CurrentLocation + "\" + DocumentName + ".docx"
'Open Word Template
On Error Resume Next 'if Word is already running
Set WordApp = GetObject("Word.Application")
If Err.Number <> 0 Then
'Launch a new instance of Word
Err.Clear
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True 'Make the application visible to the user
End If
'if document is already opened in word than close it
'if its not possible to close it - end application to prevent any damage to the template
On Error GoTo notOpen
Set WordDoc = WordApp.Documents(DocumentName + ".docx")
On Error GoTo closeError
WordDoc.Close
notOpen:
'Open the template
Set WordDoc = WordApp.Documents.Open(Filename:=Template, ReadOnly:=False) 'Open Template
'save with new name
WordDoc.SaveAs Document
closeError:
'open a message box and tell user to close and run again.
At the current stage it just jumpes from "Set WordDoc = WordApp. ..." to notOpened. Any suggestions how to solve this issue?

Add this function:
Public Function FileIsOpen(FullFilePath As String) As Boolean
Dim ff As Long
On Error Resume Next
ff = FreeFile()
Open FullFilePath For Input Lock Read As #ff
Close ff
FileIsOpen = (Err.Number <> 0)
On Error GoTo 0
End Function
Then use in your code:
If Not FileIsOpen(DocumentName & ".docx") Then
Set WordDoc = WordApp.Documents.Open(Filename:=Template, ReadOnly:=False)
Else
'Do something else because the file is already open.
End If
The document name must be the full path to the document.
Couple of other things:
Only Document is a string, and OutApp is an object. All other variables are Variants.
Dim TemplName, CurrentLocation, DocumentName, Document As String
Dim WordDoc, WordApp, OutApp As Object
It should be:
Dim TemplName As String, CurrentLocation As String, DocumentName As String, Document As String
Dim WordDoc As Object, WordApp As Object, OutApp As Object
VBA generally uses + for addition, and & for concatenation.
DocumentName + ".docx"
would be better written as
DocumentName & ".docx"
Document is a reserved word in Word. It shouldn't cause too much problem here as the code is in Excel, but something to keep in mind.

Related

Routine to open your Word document although your excel sub fails

While coding and extending the functionality of my Sub there are sadly arising some errors - e.g. a runtime error - but it could be any error...
The main topic of my question is that for me it's impossible to open that specific Word document (Test.docx) by hand (clicking on it in the explorer).
I have found one solution but this one is annoying, because I have to restart my computer and this is time consuming... and I hope there exists a more elegant solution that you can share with me.
So many thanks in advance!
Now my code with an provoked error...
Sub GetInfoOutOfWordDocument()
'Init
Dim appWord As Word.Application
Dim document As Word.Document
Dim strFolder As String
Dim strFile As String
Dim MyArray() As Variant ' for arising the error
' Select the word document
strFolder = "C:\Users\"
strFile = Dir(strFolder & "Test.docx", vbNormal)
' Open the word document
Set appWord = CreateObject("Word.Application")
Set document = appWord.Documents.Open( _
FileName:=strFolder & "\" & strFile, AddToRecentFiles:=False, ReadOnly:=False, Visible:=False)
' Getting the needed information out of your Word document...
' Now the error occurs - e.g. runtime error
MyArray(1)=5
' Problem: The above opened Word document isn't closed properly and therefore
I'm not able to open the specific Word document by hand
dokument.Close wdDoNotSaveChanges
appWord.Quit
Set document = Nothing
Set appWord = Nothing
End Sub

Passing String From Excel to Word

I am trying to pass a string from Excel userform using VBA to a Word document. In the Word document I have created a field>doc variable and called it bookingRef. The code is as follows:
Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
Set doc = objWord.Documents.Open("test.docx")
objWord.ActiveDocument.variables("bookingRef").Value = Me.txtRef.Text
objWord.ActiveDocument.Fields.Update
objWord.Documents.Save
It doesn't have any errors, however when I open the document up, I have to right click and update field (I thought objWord.ActiveDocument.Fields.Update did this?). Also, it keeps locking the document so it cannot be opened again. Is there a way to unlock after save?
The document is locked because you didn't close it with the Document.Close method, so the document is still opened and therefore cannot be opened again.
Also avoid using ActiveDocument the document that was opened is set to doc
Set doc = objWord.Documents.Open("test.docx")
and can therefore be referenced with doc.
Dim objWord As New Word.Application
Dim doc As Word.Document
'Dim bkmk As Word.Bookmark
Set doc = objWord.Documents.Open("test.docx")
doc.variables("bookingRef").Value = Me.txtRef.Text
doc.Fields.Update
doc.Save
doc.Close
Also don't forget to quit your Word application after you are done.
objWord.Quit
Otherwise the instance of Word will be open until you shut down your computer.
The Fields.Update method should update the fields, but it might be unsuccessful because of an error. Check it for errors:
If doc.Fields.Update = 0 Then
MsgBox "Update Successful"
Else
MsgBox "Field " & doc.Fields.Update & " has an error"
End If
What I did (a test according comments below this answer):
(following steps according How to store and retrieve variables in Word documents)
Created a file C:\Temp\test.docx
To use the DocVariable field, follow these steps:
On the Insert menu, click Field.
In the Categories box, select Document Automation.
In the Field names list, select DocVariable.
In the New Name box, under Field properties, type the name of the document variable bookingRef.
Click OK.
Note you will see nothing in the document yet but that's ok because the variable bookingRef does not exist yet.
Save file and close Word.
Run the following code in Excel
Option Explicit
Public Sub Test()
Dim objWord As New Word.Application
On Error GoTo CLOSE_WORD_APP 'error handling to ensure there will not be any orphaned and invisible Word application left
Dim doc As Word.Document
Set doc = objWord.Documents.Open("C:\Temp\test.docx")
doc.Variables("bookingRef").Value = "This is the updated Value: " & Time
doc.Fields.Update
doc.Save
doc.Close
CLOSE_WORD_APP:
objWord.Quit SaveChanges:=False
If Err.Number <> 0 Then
Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
End If
End Sub
Open the Word document C:\Temp\test.docx and see that everything is updated:

How to copy and paste pictures from Excel to Word

I am producing a report which needs to be run daily. I have some pictures in Excel and I want to copy them and paste them into Word. I need them in a certain location. All this needs to be done in VBA.
My proposed way of doing this is by creating template pictures in Word and giving them a name (which can be seen in Home > Select > Selection Panel). I assume that I can then copy the pictures from Excel and paste them over the template pictures (i.e. replacing the template pictures) - I believe this type of technique is possible with Excel-Powerpoint.
(1) If I can execute this, will the pictures from Excel go to the right location in Word and be of the same dimensions as the template pictures?
(2) How do I select the existing named template pictures?
Here is my code so far but at the end, I am missing the ability to select the existing NAMED template pictures...
Dim wd As Object
Dim ObjDoc As Object
Dim FilePath As String
Dim FileName As String
FilePath = "OMITTED FOR PRIVACY REASONS"
FileName = "OMITTED FOR PRIVACY REASONS"
On Error Resume Next
Set wd = GetObject(, "Word.Application")
If wd Is Nothing Then
Set wd = CreateObject("Word.Application")
Set ObjDoc = wd.Documents.Open(FilePath & "\" & FileName)
Else
On Error GoTo notOpen
Set ObjDoc = wd.Documents(FileName)
GoTo OpenAlready
notOpen:
Set ObjDoc = wd.Documents.Open(FilePath & "\" & FileName)
End If
OpenAlready:
On Error GoTo 0
wd.Visible = True
ObjDoc.
Thank you so much for your time and effort!

EXCEL VBA to Open Word, Edit and Saveas in the specified location.

Am trying to Open the Word application, Edit, Saveas in the specified location and Need to check whether user has entered the correct Filename.
Here's my code
Dim Doc
Dim DocPath
Dim DocObj
Dim VarResult
DocPath = "C:\MyFolder\MyDocument.doc"
Set DocObj = CreateObject("word.Application")
Doc = DocObj.Documents.Open(DocPath)
DocObj.Visible = True
After opening the document I am doing some changes
With Doc.ActiveDocument
Set myRange = .Content
With myRange.Find
.Execute FindText:="FindText", ReplaceWith:="ReplaceText", Replace:=2
End With
End With
Now, I have an issue in saveas the file. I used both the alternative methods,
1: GetSaveAsFilename, 2: SaveAs. I need the saveas dialog box to appear(with all DefaultLocation, InitialFilename, DocumentType, Title properties). User needs to select and the same needed to be validated, whether user has not given Cancel button.
varResult = Doc.GetSaveAsFilename( _
FileFilter:="DP Document (*.doc), *.doc, DP Document (*.docx), *.docx", Title:="Save DP", initialvalue:="InitialDocument")
If varResult <> False Then
MsgBox "File choosen = " & varResult
Else
MsgBox "Please select the file"
End If
Am getting Run-time error. Thanks in advance.
According to this Microsoft Article, "If you use the CreateObject function with an object of type Word.Application or Word.Basic, the function fails if Word is already running." The failure is indicated by a Run-Time error. Microsoft suggests that you "check to see whether Word is already running. If it is not, start a new instance of Word." For example, you could use "the GetObject function to create a Word.Application object. If the GetObject function fails, Word is not running, so the CreateObject function is then used to set the Word.Application object." The code provided in the linked article is as follows:
Sub RunWord()
Dim wObj As Word.Application
On Error Resume Next
' Get existing instance of Word if it exists.
Set wObj = GetObject(, "Word.Application")
If Err <> 0 Then
' If GetObject fails, then use CreateObject instead.
Set wObj = CreateObject("Word.Application")
End If
' Add a new document.
wObj.Documents.Add
' Exit Word.
wObj.Quit
' Clear object memory.
Set wObj = Nothing
End Sub

Modify an opened word document through Excel

How can I modify an opened word document through Excel with VBA?
Here a bit of code I'm writing, but there's something wrong I can't understand.
Dim WordDoc As Word.Document
Dim WordApp As Word.Application
'ThisWorkbook is the opened Excel Workbook through which I control Word documents.
If Len(Dir(ThisWorkbook.path & "\Report.docx")) <> 0 then
'if the document exists in the folder where ThisWorkbook is saved, I check
'if the document is already opened.
If IsFileOpened(ThisWorkbook.path & "\Report.docx")
'if during the run-time I get here, it means that the document exists and
'it's already opened.
'Now I want to get the reference to the opened document "Report.docx",
'so I do a thing like this.
Set WordDoc= Word.Application.Documents(ThisWorkbook.path & "\Report.docx")
'When it tries to excute the instruction over, it gives me a message in which
'it is written that the name is bad or inexistent, even if the document
'is already opened. Is the instruction correct?
Set WordApp= WordDoc.Application
'...other code
Else
'if the document isn't opened, I open it.
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Open(ThisWorkbook.path & "\Report.docx")
'..other code
End If
Else 'I create a new document called "Report.docx" if it doesn't exist
'in the folder where ThisWorkbook is saved.
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Add("Report.docx")
'.... other code
End If
Thanks in advance...
I tried this with an excel workbook and it worked
Set WordDoc= Word.Application.Documents(ThisWorkbook.path & "\Report.docx")
should be
Set WordDoc= Word.Documents("Report")
When I tried using the file path, I got Run-time error "9" Subscript out of range. When I used just the file name, it was successful.
Edit: After trying this with a word document, you do not need the application object and should not use the file extension. I can confirm that this works.
I tried this version
path = ThisWorkbook.path & "\Report.docx"
Set WordApp = GetObject(path).Application
in place of
Set WordDoc= Word.Application.Documents(ThisWorkbook.path & "\Report.docx")
and it works.

Resources