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.
Related
I would like to open my Word file (to make the changes then save it under different name).
I can't open my file.
My first code:
Sub RamsOpen2()
Dim Doc
Dim DocPath
Dim DocObj
Dim VarResult
DocPath = "C:\Users\mariuszk\Desktop\cf10\RAMS.docx"
Set DocObj = CreateObject("word.Application")
Doc = DocObj.Documents.Open(DocPath)
DocObj.Visible = True
With Doc.ActiveDocument
Set myRange = .Content
With myRange.Find
.Execute FindText:="FindText", ReplaceWith:="ReplaceText", Replace:=2
End With
End With
VarResult = Doc.GetSaveAsFilename( _
FileFilter:="DP Document (*.doc), *.doc, DP Document (*.docx), *.docx", Title:="Save DP",
initialvalue:="InitialDocument")
End Sub
which comes from here:
EXCEL VBA to Open Word, Edit and Saveas in the specified location.
This is roughly what I want to do with my Word file, however question is on the first step.
I have read here, that it is a common problem. VBA Excel - Unable to open existing Word Document file
I found a closer answer to my situation here: Excel macro - open specific word file
Following the advice from this query I mounted the following code:
Sub RamsOpen3()
Dim appWD As Word.Application
Set appWD = New Word.Application
Dim docWD As Word.Document
Set docWD = appWD.Documents.Open("C:\Users\mariuszk\Desktop\cf10\RAMS.docx")
appWD.Visible = True
'
' Data is selected and copied into "Design"
'
'Copy all data from Design
Sheets("Frontsheet").Select
Range("D18").Copy
' Tell Word to create a new document
appWD.Selection.Paste
' Save the new document with a sequential file name
Sheets("Sheet1").Select
appWD.ActiveDocument.SaveAs filename:=ThisWorkbook.path & "/" & "TEST" & Range("C8").Text
' Close this new word document
appWD.ActiveDocument.Close
' Close the Word application
appWD.Quit
End Sub
but the problem is the same.
Another answer is here: Excel VBA to Open Multiple Word files in a loop
but I don't want to open all Word documents in the folder.
This simple solution: VBA to open Excel or/and Word Files
also brings the same error.
As Fink pointed out in the comments your file icon looks like your file is a docm file. Since icons are chosen by file extensions there is only one solution: Check if you have file extensions turned invisible in Explorer (https://fileinfo.com/help/windows_10_show_file_extensions).
Your file is obviously called RAMS.docx.docm but you cannot see the file extension .docm.
Checkout if the following works
Set docWD = appWD.Documents.Open("C:\Users\mariuszk\Desktop\cf10\RAMS.docx.docm")
or turn on your file extension view and rename the file.
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:
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.
In my excel document I have a chart that I want to copy and paste into a MS-Word document. I want to avoid linking data, embedding workbooks and resizing (Excel has the chart formatted to my desired size). So I came up with/found the following code that almost works:
Sub PasteChart()
Dim wd As Object
Dim ObjDoc As Object
Dim FilePath As String
Dim FileName As String
FilePath = "C:\Users\name\Desktop"
FileName = "Template.docx"
'check if template document is open in Word, otherwise open it
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
'find Bookmark in template doc
wd.Visible = True
ObjDoc.Bookmarks("LPPU").Select
'copy chart from Excel
Sheets("Group Level Graphs").ChartObjects("Chart 1").Chart.ChartArea.Copy
'insert chart to Bookmark in template doc
wd.Selection.PasteSpecial Link:=False, DataType:=14, Placement:=0, _
DisplayAsIcon:=False
End Sub
The only issue is that the image is pasted as "In Line with Text" but I need it to be "Square with text wrapping". I can't get Word or Excel to record changing the image to "Square with text wrapping".
The PasteSpecial part only does wdFloatOverText or wdInLine for placement and neither of them solve this issue.
I am very new to VBA and have run out of ideas. I am still trying to find a way to format it, maybe using some kind of WITH statement. However I thought I would attempt to reach out for help while I continue google-foo and learning VBA from Youtube.
Using PasteAndFormat Type:=wdChartPicture links the chart to excel. So that didn't work.
Make sure you have a reference to the Word application in your VBE then immediately following a regular paste (wd.Selection.Paste), add these two lines of code:
wd.Selection.MoveStart word.WdUnits.wdCharacter, Count:=-1
wd.Selection.InlineShapes(1).ConvertToShape.WrapFormat.Type = wdWrapSquare
If you want to continue to use the PasteSpecial method you have in your code then replace the code line above "wd.Selection.MoveStart..." to this:
wd.Selection.MoveEnd word.WdUnits.wdCharacter, Count:=1
The reason is a regular paste leaves the active insertion point at the end of the inserted object. But if a PasteSpecial method is used the active insertion point is at the beginning of the object that was pasted. Why? I have no idea! Word VBA never ceases to amaze me. :-)
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