How to make sure from Excel that a specific Word document is open or not? - vba

I wanted my excel macro to create a report by inserting spreadsheet data after Bookmarks I placed in the template word documents.
But I found out that if the template word document is already open, the macro will crash, and consequently the template document will be locked as Read-only and no longer accessible by the macro.
Is there a way to prevent then macro from crashing even if the template word document is already open?
Below is my code
Set wdApp = CreateObject("Word.Application") 'Create an instance of word
Set wdDoc = wdApp.Documents.Open(ThisWorkbook.Path & "\Templates\Template_Confirmation.docx") 'Create a new confirmation note

Here comes an evolution of what was suggested in comments :
A function that test if the file is open and offer you to set it directly while testing.
How to use it :
Sub test()
Dim WdDoc As Word.Document
Set WdDoc = Is_Doc_Open("test.docx", "D:\Test\")
MsgBox WdDoc.Content
WdDoc.Close
Set WdDoc = Nothing
End Sub
And the function :
Public Function Is_Doc_Open(FileToOpen As String, FolderPath As String) As Word.Document
'Will open the doc if it isn't already open and set an object to that doc
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
On Error Resume Next
'Set wrdApp = GetObject(, "Word.Application")
If wrdApp Is Nothing Then
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open(FolderPath & FileToOpen)
Else
On Error GoTo NotOpen
Set wrdDoc = wrdApp.Documents(FileToOpen)
GoTo OpenAlready
NotOpen:
Set wrdDoc = wrdApp.Documents.Open(FolderPath & FileToOpen)
End If
OpenAlready:
On Error GoTo 0
Set Is_Doc_Open = wrdDoc
Set wrdApp = Nothing
Set wrdDoc = Nothing
End Function
Only downside of this, you don't have the reference of the Word application...
Any suggestion/evolution are welcome!

Related

how to use an already open document from another module?

i write in a word.document. When it is necessary i write a paragraph in another document and when i finish this document is closed. then i try to copy this paragraph to the first document which remains open.
I try some things but in vain.
when i do this:
Dim wdDocMain As Word.Document
Set wdDocMain = ActiveDocument
i receive the message run time error 4248 This command is not available because no document is open.
when i do this
Dim wdDocMain As Word.Document
Set wdDocMain = wdApp.Documents.Open(FileName:=pathmaindoc,_ ReadOnly:=False, Visible:=True)
wdDocMain.Activate
i receive the message run time error 91 object variable or with block variable not set.
i find a solution.
To close the open document and then to reopen it like this:
Set wdDocMain = wdApp.Documents.Open(FileName:=pathmaindoc,_ ReadOnly:=False, Visible:=True)
but of cource it isnt the best.
Edit.
I would like to thank you in advance for your comments.
i share more lines from my code as Timothy Rylatt suggested.
In my main sub:
Dim wdapp As Word.Application
Dim wdDoc As Word.Document
Set wdapp = New Word.Application
Set wdDoc = wdapp.Documents.Open(FileName:=PathName_HiveDown_Creation,_ ReadOnly:=False, Visible:=True)
wdapp.Visible = True
when a condition is met then i call a module (copyparafromtemplatetomain):
pathmaindoc = PathName_HiveDown_Creation
pathtemplatedoc = PathName_Template
'wdDoc.Close savechanges:=True
copyparafromtemplatetomain
Public wdapp As Word.Application
Public wdDocMain As Word.Document
Sub copyparafromtemplatetomain(pathmaindoc As Variant, pathtemplatedoc As Variant, paramain As Variant, paratemplate As Variant, index As Integer)
Dim wdDocTemplate As Word.Document
Dim PathName_MainDoc As Variant
PathName_MainDoc = pathmaindoc
Set wdDocMain = wdapp.ActiveDocument
here, i receive run time error 91.
the only way to run is when i close the doc. in the first sub

How to open Word Application using vba

I have a code. It does not run in 2016.Is it a Office 16 problem
Dim objWordApp as Word.Application
Dim objWordDoc as Word.document
Set objWordApp = new Word.application
I get an error Error in loading DLL .I have already included the library Microsoft word 16.0 Object Library
regards
Anna
I am not sure what went wrong for you but if you just want to open a new word document with your default MS office then you can use this peace of code
Sub wordopener()
Dim objWord
Dim objDoc
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
objWord.Visible = True
End Sub
I generally have a BAS file containing the 'CreateWord' function which I drag into any workbook/database that needs it.
First it tests to see if Word is already open using GetObject. If that returns an error it creates an instance of Word using CreateObject.
The Word application can then be opened by simply using Set oWD_App = CreateWord.
Sub Test()
Dim oWD_App As Object
Dim oWD_Doc As Object
Set oWD_App = CreateWord
With oWD_App
Set oWD_Doc = .Documents.Add
End With
End Sub
Public Function CreateWord(Optional bVisible As Boolean = True) As Object
Dim oTempWD As Object
On Error Resume Next
Set oTempWD = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Err.Clear
On Error GoTo ERROR_HANDLER
Set oTempWD = CreateObject("Word.Application")
End If
oTempWD.Visible = bVisible
Set CreateWord = oTempWD
On Error GoTo 0
Exit Function
ERROR_HANDLER:
Select Case Err.Number
Case Else
MsgBox "Error " & Err.Number & vbCr & _
" (" & Err.Description & ") in procedure CreateWord."
Err.Clear
End Select
End Function
You are trying to use early binding. It is advisable, because it is a bit faster and it gives you intellisense, which is nice. However, to use it, you should add the corresponding libraries.
However, if you use the slower late binding, you do not need to add any libraries. It does not have intellisense and it would be a bit slower (but probably not noticeable).
Try like this:
Option Explicit
Sub TestMe()
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
objWord.Visible = True
End Sub
Early binding vs. late binding: what are the comparative benefits and disadvantages?

VBA excel nesting data from excel into a table in word (copying excel data into Word table)

I'm trying to paste a table into word from excel with VBA Excel.
I'm pasting it into a cell in a single column table of 4 rows I created in Word. So it is essentially a nested table.
I keep getting,
Run-time error 4605: Method 'PasteAsNestedTable' of object Selection failed
I'm trying to use PastAsNestedTable because otherwise I get the Run-time error about cells not matching as it is trying to merge the two tables.
So I get it is saying PasteAsNestedTable isn't a method of selection but how do I get around this issue?
My updated code goes:
Dim wdApp As Word.Application
Dim wdDoc as Word.Document
Dim tabl1 as Table, tabl2 as Table
Set wdApp = new Word.Application
With wdApp
.visible = True
.Activate
.Document.Add(location)
Set wdDoc=wdApp.ActiveDocument
With wdApp
Charts("chart1").ChartArea.Copy
.Selection.GoTo what:=-1,Name:="chart1"
.selection.Paste
(Then add some more charts)
End With
Sheets("Sheet1").Range("A1:F10").Copy
Set wdDoc=wdApp.ActiveDocument
wdDoc.Bookmarks("table").Range.PasteAsNestedTable
With wdApp
(Then repeat above pasting charts + tables)
`
If I made the Range a ListObjects could I somehow copy it in that way?
Don't use Selection.
This here works for me (Word with correct document already opened):
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Set wdApp = GetObject(, "Word.Application")
Sheets(1).Range("A1:F10").Copy
Set wdDoc = wdApp.ActiveDocument
wdDoc.Bookmarks("tableplace").Range.PasteAsNestedTable
You can of course replace GetObject(, "Word.Application") with your new Word.Application and set wdDoc as wdApp.Documents.Open(pathtoyourdoc).
Then combine with my answer from your other thread, replace wdthere with wdDoc and you should be good to go.
Edit I have changed my code to reflect your current variables and bookmark names:
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim tabl1 As Table, tabl2 As Table
Set wdApp = New Word.Application
With wdApp
.Visible = True
.Activate
Set wdDoc = .Documents.Open(Location)
End With
Charts("chart1").ChartArea.Copy
wdDoc.Bookmarks("chart1").Range.Paste
Sheets("Sheet1").Range("A1:F10").Copy
wdDoc.Bookmarks("table").Range.PasteAsNestedTable
'(Continue like this for other charts + tables)
Note:
Do not use Douments.Add, as this will add a new empty document based on a template. This will not have your bookmarks. Use .Open instead.
Close With blocks properly
Do not set the same object over and over again. Set it once and work with that object
Do not use Selection unless absolutely necessary. Not necessary in this case.
You can set DocVariables in Word. Google this if you don't know how to do this. Then, run the script below, from Excel.
Sub PushToWord()
Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
sWdFileName = Application.GetOpenFilename(, , , , False)
Set doc = objWord.Documents.Open(sWdFileName)
'On Error Resume Next
objWord.ActiveDocument.variables("FirstName").Value = Range("FirstName").Value
objWord.ActiveDocument.variables("LastName").Value = Range("LastName").Value
objWord.ActiveDocument.variables("Another").Value = Range("Another").Value
objWord.ActiveDocument.Fields.Update
'On Error Resume Next
objWord.Visible = True
End Sub

VBA copying from Excel file to WORD file bookmark

When I copy a chart from Excel ('Report' sheet) to a WORD file ('Report template.docx'), why does VBA wipe out the previous content of the WORD file? I suspect the problem is in line 'wddoc.Range.Paste' but I don't know how to change it to avoid the problem.
Sub ActivateWordTransferData()
Dim wdapp As Object, wddoc As Object
Dim strdocname As String
Set wdapp = GetObject(, "Word.Application")
wdapp.Visible = True
strdocname = "C:\users\ian\Documents\Dropbox\Report template.docx"
Set wddoc = wdapp.documents(strdocname)
Worksheets("Report").Shapes("Chart 2").Copy
wdapp.Activate
wddoc.bookmarks("bkmark4").Select
wddoc.Range.Paste
wddoc.Save
Set wddoc = Nothing
Set wdapp = Nothing
Application.CutCopyMode = False
End Sub
I'm not sure why the contents of the Word document are being overwritten.
However, removing the .Select operation and just pasting into the bookmark's range seems to work.
Remove these lines:
wddoc.bookmarks("bkmark4").Select
wddoc.Range.Paste
and replace with this line:
wddoc.bookmarks("bkmark4").Range.Paste

VBA - Object doesn't support this property or method

I am receiving the error "Object doesn't support this property or method", in Excel after I changed part of my code. The line that is throwing the error is "With odoc.MailMerge" Here is the code:
strBookName = "\" & "PM MailMerge.xlsm"
strBookPath = ActiveWorkbook.Path
strBook = strBookPath & strBookName
'Opens Word.Application
Set ObjWord = CreateObject("Word.Application")
Set odoc = GetObject(strBook)
'Executes a Hidden Mail Merge
ObjWord.Visible = False
With odoc.MailMerge
.Destination = wdSendToNewDocument
With .DataSource
.FirstRecord = 1
.LastRecord = 1
odoc.MailMerge.Execute
Set odoc2 = odoc.Application.documents("Form Letters1")
odoc.Close True
End With
End With
Try
option explicit
Dim objWord as Word.Application
Dim oDoc as As Word.Document
Set ObjWord = CreateObject("Word.Application")
set oDoc = objWord.documents.Open strBook
Don't forget to reference the Word library in the menu: tools > references.
By the way: Dim all your variables (force with option explicit).
Edit:
Note: the file that you mention in your code sample is an Excel .xlsm, not a Word .doc...
Set odoc = GetObject(strBook) is this a workbook for excel? if so there is no MailMerge method for a workbook object. You need to reference a word document to use the MailMerge Method of the Document objet