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:
Related
I'm opening a preexisting word document with Excel VBA and add some data to it and then I just want to save this file. But when I run the Excel VBA macro the word "save as" window appears.
And that's not my aim.
The word document should just be saved... (like when you add some data to the word document by hand and then press CTRL+S)
If more details are needed let me know... And many thanks for your help in advance.
Now my code:
Dim appWord As Word.Application
Dim document As Word.Document
Set appWord = CreateObject("Word.Application")
' the excel file and the word document are in the same folder
Set document = appWord.Documents.Add( _
ThisWorkbook.Path & "\Testfile.docx")
' adding the needed data to the word file
...
' in this following line of code I tried to do the correct saving... but it opens the "save as" window - I just want to save it automatically
document.Close wdSaveChanges = -1
'Close our instance of Microsoft Word
appWord.Quit
'Release the external variables from the memory
Set document = Nothing
Set appWord = Nothing
Set document = appWord.Documents.Add( _
ThisWorkbook.Path & "\Testfile.docx")
You’re not opening a document with this code, you’re creating a new, unsaved, document from an existing one. Change it to:
Set document = appWord.Documents.Open( _
ThisWorkbook.Path & "\Testfile.docx")
You’re also missing a colon.
document.Close wdSaveChanges:=-1
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.
I have a macro launched from Excel to control a Word document.
In order to prevent issues with references (Microsoft Word 15.0 Object Library or Microsoft Word 16.0 Object Library for example) I use late binding in the main macro :
Public appWord as Object
Sub MainSub()
Set appWord = GetObject(, "Word.Application")
If appWord Is Nothing Then
Set appWord = CreateObject("Word.Application")
End If
'Create temp file'
'...'
'Open temp file = strTempWordFile'
Set docWord = appWord.Documents.Open(strTempWordFile)
'Launch function to search text and remove it from the word document
SearchAndRemove rgCell2.Text, docWord
End Sub
Here is an extract of the function (in another module)
Sub SearchAndRemove(ByVal strSearchWord As String, ByRef docWord As Word.Document)
Set selWordSelection = appWord.Selection 'That works
selWordSelection.HomeKey Unit:=wdStory 'line with issue
'do the search and remove'
End Sub
If the Sub is called via declaring docWord as Word.Document (which requires reference to Microsoft Word 1X.0 Library, this line works OK :
selWordSelection.HomeKey Unit:=wdStory
If the Sub is called via declaring docWord as Object (which does not require reference to Microsoft Word 1X.0 Library, this line does not work anymore.
If you don't know the numerical equivalent then:
Open the application in question (in your case Word)
Open the VBE (Alt + F11)
Open the Immediate window (Ctrl + G)
Enter the keyword in the immediate window preceded by a ? (?wdStory)
Use the number it returns in your code.
In this case you need to replace wdStory with the number 6.
(and just read the middle line of #AlexK comment - add a reference temporarily and ?wdStory in the immediate window to see what it is)
Never thought of adding the referencing and using the immediate window in the current app. I know I'd forget to remove it again though.
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
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.