Search code examples
vbaautomationms-word

How do I open then activate a document


My VBA is no longer supporting the code that was working before.

When I tried Objword.Documents.Open and then docword.Activate, the document is opened but I get

4248 Run time error, "the command is not available because no document is open".

VBA macro references has the MS Office 16 Object Library selected.

ObjWord.Visible= True
Dim docword As object
Dim OCC as ContentControl

ObjWord.Activate

Set docWord = objWord.Documents.Open( Filename)
docWord.Activate-------Error
For each oCC In ActiveDocument.ContentControls
    Select  Case Occ.Title
        Case abc
            Occ.Range.Text

Solution

  • As you have set a variable for the document you have opened you should not be using ActiveDocument. Your code should run regardless of whether the newly opened document is activated.

    So, assuming your code is not being run from Word it should be:

    ObjWord.Visible= True
    Dim docWord As Document
    Dim OCC as ContentControl
    
    ObjWord.Activate
    
    Set docWord = objWord.Documents.Open(Filename)
    For each oCC In docWord.ContentControls
     
      Select  Case Occ.Title
        Case abc
         Occ.Range.Text