## Start Your First Python Project in 3 Steps: Grab Your Free Online Course Right Now!

The error I made in the past was writing documents by hand, which was more time consuming and error-prone. Additionally, the document was of a more modest quality and never up to date.
The solution was to automate the generation of the documentation.

## 1. Opening and Closing a Word File from MATLAB

### 1.1. Theory

If you want to write data into a Word file, you first need to open it. The function below has been created to open a word file and to output a structure that will be used to identify the file you want to write on:

function fid = fopenWord(wordFile)
word = actxserver('Word.Application');
word.Visible = 1;
if ~exist(wordFile, 'file');
% create new document:
invoke(fid.handle, 'SaveAs', [pwd '/' wordFile]);
else
% open existing document:
fid.handle = invoke(word.Documents, 'Open', [pwd '/' wordFile]);
end
fid.actx = word;
return

This function will:

1. Open a Word file with the name given by the variable wordFile if the file already exists in the current folder.
2. Open a new Word file with the name given by the variable wordFile if the file does not already exist.

When you are done with writing into the file, you then need to close it:

function fcloseWord(fid)
handle = fid.handle;
word = fid.actx;
% save the Word file
invoke(handle, 'Save');
% close Word
word.Quit();
return

### 1.2. Practice

Below is an example of using the 2 functions. In this example, we create a new Word file, save it and close it, and then open the file as if you clicked on it from your computer.

clc
winopen(wordFile);