Activate an Open Word Document

Apologies. I have posted this question (in part) before, but have not had an answer.

 

I have an Excel VBA UserForm with several CommandButtons. I am using the CommandButtons to invoke a Help facility, whereby the topic numbers relate to bookmarks in a Word document. This part works OK.

 

I have written the following code .....

 

Private Sub OpenHelpDocument(strTopic)
Dim strPath As String
strPath = "C:\My Documents\Help Topics.doc"
Dim objWord As Object
Dim docWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
    If funIsDocOpen(strPath) = True Then

        MsgBox "Testing"
        Set docWord = objWord.documents.Activate(Filename:=strPath)   ' **** This code fails ***
    Else
        Set docWord = objWord.documents.Open(Filename:=strPath, ReadOnly:=True)
    End If
docWord.Bookmarks(strTopic).Range.Select
End Sub

 

When the sub 'OpenHelpDocument' is run for the first time, the function 'funIsDocOpen' correctly returns 'False' and the Word Document 'Help Topics.doc' opens in read-only mode at the correct bookmark. So far, so good.

 

However, when run for a second time with a new topic (with 'Help Topics.doc' already open), it fails "Run-time error '438': Object doesn't support this property or method". The MsgBox "Testing" is displayed prior to the error message.

 

I want the Word Document to remain open and available for (potentially) multiple Help/Topic/Bookmark enquiries. It will be closed later.

 

How can I 'Activate' the existing Open Document when the function returns 'True'? I am assuming that 'Activate' is the correct teminology!!

 

Thanks in anticipation, and apologies again for a repeated question.

 

Answer
Answer

Replace

 

    Set objWord = CreateObject("Word.Application")

 

With

 

    On Error Resume Next

    Set objWord = GetObject(, "Word.Application")
    If Err <> 0 Then
        Set objWord = CreateObject("Word.Application")
    End If

Hope this helps,
Doug Robbins - MVP Office Apps & Services (Word)
dougrobbinsmvp@gmail.com
It's time to replace ‘Diversity, Equity & Inclusion’ with ‘Excellence, Opportunity & Civility’ - V Ramaswamy

4 people found this reply helpful

·

Was this reply helpful?

Sorry this didn't help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

 
 

Question Info


Last updated November 25, 2024 Views 5,297 Applies to: