I am creating a database for someone which includes a mail merged document with some data from the database.
Is it possible to allow the user to open the document by clicking on a button that will be on the Switchboard in the database, so that they do not have manually open the document?
Hope this makes sense!
Microsoft's technical documents are rarely very useful as a training tool, so here you go.
Word, like Access, is an application. According to Windows, each application is its own object. All the objects in MS Office can talk to each other and transfer things between each other, very similar to how a form can "talk" to a subform and vice-versa.
Therefore, Access can treat Word like another object, and it can be accessed and treated as one. You have to go to References in the Tools menu in the VBA code editing window, and you have to add the Word reference. It will be called "Microsoft Word [version_number] Object Library".
From here, you have to declare the object. Do this explicitly, like this:
Code:
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
You do not want to use Dim WordApp As New Word.Application as that can cause all sorts of weirdness since it tells Access to instantiate your application instead of giving you control.
After you've declared the application and document objects like shown above, you want to instantiate them and open the document you want, like this:
Code:
Set WordApp = New Word.Application
Set WordDoc = New Word.Documents.Open FileName:=[Your path/filename here]
That will open Word and the document you want to open from within Access.
Keep in mind that in dealing with Word or any other application object from within Access, you want to be explicit in all your calls to it. For example, to count the number of words in the document, the command is this:
WordApp.ActiveDocument.Words.Count
In the VBA environment, this looks like it would work:
ActiveDocument.Words.Count
In fact, the second example will work on the first try. When you try to run the exact same code a second time, you will get a cryptic error message (something about a remote server, which has nothing to do with the actual problem). It's because you didn't explicitly tell Access what ActiveDocument you meant (even though it's clear you mean the Word document). I personally think this is just a flaw in Access/VBA, but I learned it the hard way, so I'm passing it on. The first method (explicitly calling the word count through the WordApp object) will work every time.
This will seem breally stupid but
Am I creating a new module to enter the code in?
As you can obviously not attach the VB code to an object in the database.
Correct. You are making a module for the code. The easiest thing to do is to make a form with an "Open Document" button on it. Put that code behind the document's OnClick event.