Open the Word file in the active Workbook directory - excel

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?

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

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.

Opening the Word file in 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

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

Check if Word Document is already opened + Error Handling

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.

Resources