# VBA to close open Word document



## oseitutuSamuel (Dec 8, 2018)

Hi People,

I use the function below in Excel VBA to open different Word documents one at a time. I pass the Word document's name as a parameter to this function to open it.
Please kindly show me how I can write another code to close a document that is already opened before I open another one.

Many thanks:

Public Function FnOpenWordDoc(strWordDoc)
    Dim wordApp As Word.Application
    Set wordApp = CreateObject("Word.Application")
    wordApp.Documents.Open (strWordDoc)
    wordApp.Application.WindowState = wdWindowStateMaximize
    wordApp.ActiveWindow.ActivePane.View.Zoom.Percentage = 100
    wordApp.Visible = True
    wordApp.Activate
End Function


----------



## Jaafar Tribak (Dec 8, 2018)

Something like this :

```
Public Function FnOpenWordDoc(strWordDoc) As Object
    Dim wordApp As Object
    
    On Error Resume Next
        Set wordApp = GetObject(, "Word.Application")
    On Error GoTo 0
    If wordApp Is Nothing Then
        Set wordApp = CreateObject("Word.Application")
    End If
    With wordApp
        Set FnOpenWordDoc = .Documents.Open(strWordDoc)
        .WindowState = wdWindowStateMaximize
        .ActiveWindow.ActivePane.View.Zoom.Percentage = 100
        .Visible = True
        .Activate
    End With
End Function
```

And then when using the function, try something along these lines :

```
Sub test()

    Dim oDoc As Object
    
    Set oDoc = FnOpenWordDoc("D:\MyWordDoc.docm")

    
    [COLOR=#008000][B]' Do your stuff here ....[/B][/COLOR]
    

    [B][COLOR=#008000]'Close the Word document.[/COLOR][/B]
    If Not oDoc Is Nothing Then
        oDoc.Close  [B][COLOR=#008000]'<==optionally Set the savechanges arg to True before closing the word document[/COLOR][/B]
    End If
End Sub
```


----------



## Macropod (Dec 8, 2018)

Alternatively, something like:

```
Public Function FnOpenWordDoc(strWordDoc)
Dim wdApp As New Word.Application, wdDoc As Word.Document
With wdApp
  .Visbible = False
  Set wdDoc = .Documents.Open(Filename:=strWordDoc, AddToRecentFiles:=False)
  With wdDoc
    'do stuff, then
    .Close SaveChanges:=True
  End With
  .Quit
End With
End Function
```
There is no particular reason to mess with Word's display setting, or even have it visible, if all you're doing is editing a document before closing it with saved changes.


----------



## oseitutuSamuel (Dec 9, 2018)

Hello Jaafar & Macropod,
Many thanks for taking your time to help with my code. I am truly grateful. I spent many hours on it but couldn't get it working.
Between you and Macropod, you have "Killed the beast"

Regards,
Samuel


----------

