vba - How to make sure from Excel that a specific Word document is open or not? -
i wanted excel macro create report inserting spreadsheet data after bookmarks placed in template word documents.
but found out if template word document open, macro crash, , consequently template document locked read-only , no longer accessible macro.
is there way prevent macro crashing if template word document open?
below code
set wdapp = createobject("word.application") 'create instance of word set wddoc = wdapp.documents.open(thisworkbook.path & "\templates\template_confirmation.docx") 'create new confirmation note
here comes evolution of suggested in comments :
a function test if file open , offer set directly while testing.
how use :
sub test() dim wddoc word.document set wddoc = is_doc_open("test.docx", "d:\test\") msgbox wddoc.content wddoc.close set wddoc = nothing end sub and function :
public function is_doc_open(filetoopen string, folderpath string) word.document 'will open doc if isn't open , set object doc dim wrdapp word.application dim wrddoc word.document on error resume next 'set wrdapp = getobject(, "word.application") if wrdapp nothing 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, don't have reference of word application...
any suggestion/evolution welcome!
Comments
Post a Comment