Opening the Word file in Excel - excel

I have managed with opening the Word file in Excel thanks to the help of some of you.
Open the Word file in the active Workbook directory
VBA Excel problem with opening the Word file
Unfortunately, I still have some smallish bugs in it. Whilst my word file is opened, the debugger says, that the script is out of range.
Theoretically, I understand it, because we are jumping to the file, which is not directly served by VBA Excel, although is it possible to get rid of this error at all?
My code looks as follows:
Sub RamsOpen3()
Dim appWD As Word.Application
Set appWD = New Word.Application
Dim docWD As Word.Document
Set docWD = appWD.Documents.Open(ActiveWorkbook.path & "\RAMS.docx.docm")
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

If you are using Cut and Paste, then you must activate the workbook first.
Bonus notes:
You're missing the file extension in the saveAs line.
This only pastes at the top of the file, if you want to go to the end, you could add the code
Selection.EndKey Unit:=wdStory
after the activate
Sub RamsOpen3()
Dim appWD As Word.Application
Set appWD = New Word.Application
Dim docWD As Word.Document
Set docWD = appWD.Documents.Open(ActiveWorkbook.path & "\RAMS.docx.docm")
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.activate 'Activate the workbook here.
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 & ".docm" 'NOTE: YOU must add the extension
' Close this new word document
appWD.ActiveDocument.Close
' Close the Word application
appWD.Quit
End Sub

Related

Open the Word file in the active Workbook directory

I am trying to set the path to my Workbook file, which I want to be opened from the same directory, where my current workbook is based.
I saw some solution here:
Open File Without Calling Filepath
and my code currently looks like this:
Sub RamsOpen3()
Dim appWD As Word.Application
Set appWD = New Word.Application
Dim docWD As Word.Document
Set docWD = appWD.Documents.Open ActiveWorkbook.Path & "RAMS.docx.docm")
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
The line of code is in red, and the debugger says: Expected end of statement.
It excludes also the option with Dim filename as string, proposed in the linked query above.
Does anyone know how to coup with it?

Opening a Word file

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.

Copy paste a table from excel to a bookmarked location in Word using VBA

I am trying to Copy and table from a sheet in excel and paste it into a word document, in a specific place, using VBA
I have tried the code below:
Sub Copypastetabe()
Dim strPath As String
'Set path via this excel workbook
strPath = ThisWorkbook.Path & "\" & "Morning Snapshot1" & ".docx"
Dim objWord As Object
Dim docWord As Object
'copy the date table to go to word doc
Sheets("Sheet4").Range("A1:F6").Copy
'define and open word doc
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set docWord = objWord.Documents.Open(fileName:=strPath, ReadOnly:=False)
'Select bookmark in word doc
docWord.Bookmarks(BondYields).Select
Selection.Paste
End Sub
I get the error
Runtime error 5941
"The requested Member of the collection does not exist"
The bookmark exists in this word document under this name, so i'm a bit stuck
Please can anyone help?
'Select bookmark in word doc
docWord.Bookmarks(BondYields).Select
Selection.Paste
Should be:
'Select bookmark in word doc
docWord.Bookmarks(“BondYields”).Select
objWord.Selection.Paste
Or better still:
‘Paste into bookmark in Word doc
docWord.Bookmarks("BondYields").Range.Paste
Probably:
docWord.Bookmarks("BondYields").Range.Paste

Edit Word document embedded in a workbook and save as copy

I have made a Word template and inserted it to Excel as an object. I am opening it with the code and inputting data to bookmarks and main part. However after code is done doing processes my embedded template has all the data inside. So it is not a template anymore but a file I have created with the code.
Embedded Word template should be opened as a copy, as I do not want to make any changes to original embedded template or null it with the code all the time (or is it the only way it possible to do?). Is it anyhow possible with the code to open embedded Word document as a copy, make changes to it and save as a Word document? I can't find anything useful in the internet.
Sub opentemplateWord()
Dim sh As Shape
Dim objWord As Object ''Word.Document
Dim objOLE As OLEObject
Dim wSystem As Worksheet
Dim cell As Range
Set wSystem = Worksheets("Templates")
''The shape holding the object from 'Create from file'
''Object 2 is the name of the shape
Set sh = wSystem.Shapes("Object 2")
''Activate the contents of the object
sh.OLEFormat.Activate
''The OLE Object contained
Set objOLE = sh.OLEFormat.Object
''This is the bit that took time
Set objWord = objOLE.Object
'>------- This Part Inputs Bookmarks
objWord.Bookmarks.Item("ProjectName1").Range.Text = ThisWorkbook.Sheets("MAIN").Range("D15").Value
objWord.Bookmarks.Item("ProjectName2").Range.Text = ThisWorkbook.Sheets("MAIN").Range("D16").Value
'>------- This Part Inputs Text
'ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument '<--- This is for closing footer and header?
With objWord '<--| reference 'Selection' object
For Each cell In ThisWorkbook.Worksheets("Offer Letter").Range("C1", ThisWorkbook.Worksheets("Offer Letter").Range("C" & Rows.Count).End(xlUp))
Select Case LCase(cell.Value)
Case "title"
.TypeParagraph
.Style = objWord.ActiveDocument.Styles("Heading 1")
.TypeText Text:=cell.Offset(0, -1).Text
Case "main"
.TypeParagraph
.Style = objWord.ActiveDocument.Styles("Heading 2")
.TypeText Text:=cell.Offset(0, -1).Text
Case "sub"
.TypeParagraph
.Style = objWord.ActiveDocument.Styles("Heading 3")
.TypeText Text:=cell.Offset(0, -1).Text
Case "sub-sub"
.TypeParagraph
.Style = objWord.ActiveDocument.Styles("Heading 4")
.TypeText Text:=cell.Offset(0, -1).Text
End Select
Next cell
End With
objWord.Application.Visible = False
''Easy enough
objWord.SaveAs2 ActiveWorkbook.Path & "\" & Sheets("Other Data").Range("AN2").Value & ", " & Sheets("Other Data").Range("AN7").Value & "_" & Sheets("Other Data").Range("AN8").Value & "_" & Sheets("Other Data").Range("AX2").Value & ".docx"
End Sub
This is an interesting task which I haven't looked at in a few years... The trick is to open the document in the Word application interface, instead of in-place in Excel.
I've adapted the code in the question. In order to make it easier to follow (shorter) I've removed the editing in the Word document except for writing to a couple of bookmarks. That can, of course, be put back in.
I very much recommend using VBA to assign a name to the Shape. Office applications feel free to change a generic name they assign, so relying on "Object 2" could, sometime down the line, lead to problems.
Do NOT use the Activate method in this scenario (commented out). If the object is already activated in-place the document cannot be opened in the Word.Application.
Use the OLEFormat.Object.Verb method with the parameter xlOpen to open the document in Word.
Once it's open, the OLE object can be set to a Word document object.
From your comments: 'ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument '<--- This is for closing footer and header? No. Better to work with the corresponding Range objects. There are lots of examples "out there" for that. Ask a new question if you run into problems using them.
A Word document opened in the Word application can be saved as a file (a document opened in-place cannot). The question about not saving edits, however... there are two basic approaches:
SaveAs before editing, open that document, edit and save. The original should then be untouched
Do the editing in the object, save then undo the changes. This approach is shown in the code sample
Word's object model is able to group any number of actions into a single "undo record".
Set objUndo = objWord.Application.UndoRecord
objUndo.StartCustomRecord "Edit In Word"
After the editing has been done, to get back to an "empty" (unchanged) document:
objUndo.EndCustomRecord
Set objUndo = Nothing
objWord.Undo
Finally, to close the document quit the Word application without saving changes.
Sub opentemplateWord()
Dim sh As Shape
Dim objWord As Object, objNewDoc As Object ''Word.Document
Dim objOLE As OLEObject
Dim wSystem As Worksheet
Dim cell As Range
Set wSystem = Worksheets("Templates")
''The shape holding the object from 'Create from file'
''Object 2 is the name of the shape
Set sh = wSystem.Shapes("WordFile")
''The OLE Object contained
Set objOLE = sh.OLEFormat.Object
'Instead of activating in-place, open in Word
objOLE.Verb xlOpen
Set objWord = objOLE.Object 'The Word document
Dim objUndo As Object 'Word.UndoRecord
'Be able to undo all editing performed by the macro in one step
Set objUndo = objWord.Application.UndoRecord
objUndo.StartCustomRecord "Edit In Word"
With objWord
.Bookmarks.Item("ProjectName1").Range.Text = ThisWorkbook.Sheets("MAIN").Range("D15").Value
.Bookmarks.Item("ProjectName2").Range.Text = ThisWorkbook.Sheets("MAIN").Range("D16").Value
objWord.SaveAs2 ActiveWorkbook.Path & "\" & Sheets("Other Data").Range("AN2").Value & _
", " & Sheets("Other Data").Range("AN7").Value & "_" & _
Sheets("Other Data").Range("AN8").Value & "_" & _
Sheets("Other Data").Range("AX2").Value & ".docx"
objUndo.EndCustomRecord
Set objUndo = Nothing
objWord.Undo
.Application.Quit False
End With
Set objWord = Nothing
End Sub
I am doing the same thing and used this post for reference.
I got rid of objUndo object and CustomRecord methods.
Instead, I used the Duplicate method on the OLEobject to protect the original emmbedded doc from being edited. Seemed easier this way. The previous duplicates get removed at beginning so they don't pile up to infinity.
Sub opentemplateWord_v2()
Dim wSheet As Worksheet
Dim sh As Shape
Dim objOLE As OLEObject '<-- og emmbeded doc
Dim objOLE2 As OLEObject '<-- duplicate doc
Dim objWord As Object
Set wSheet = Worksheets("TemplateSheet") '<-- worksheet embedded doc is on
'--remove all duplicates from previous runs
'
' *the original embedded doc is named 'Object 1'
' (seen by clicking on doc --> the 'Name Box' is at the top left)
'
For Each sh In wSheet.Shapes
If sh.Name <> "Object 1" Then sh.Delete
Next
Set sh = wSheet.Shapes("Object 1") '<-- set the shape to the embedded doc Object
Set objOLE = sh.OLEFormat.Object '<-- get the embedded object in shape
Set objOLE2 = objOLE.Duplicate '<-- create duplicate of embedded object
objOLE2.Verb xlOpen '<-- open duplicate doc in the Word application
Set objWord = objOLE2.Object '<-- The Word document
'~~~~~~~ do the stuff here ~~~~~~~~~~~~~~~~~~~~~~~~~
'
' for mine, I am going to find/replace keyfeilds on the document
' (this example is replacing "Planet" with "earth"
'
With objWord.Content.Find
.text = "Planet"
.Forward = True
.MatchWholeWord = True
.MatchCase = False
.Wrap = 1 'wdFindContinue
.Execute Replace:=1 'wdReplaceOne
If .Found = True Then .Parent.text = "earth"
End With
'-- No Save Action
' I amsume the user will want view/edit the output after execution,
' and save it in a specific place
'
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