Form.Hide vs End

I

Iain McLaren

Hi,

I have come across a strange problem in Word/VBA 2003. I have a macro that
runs when the user tries to print a document. It opens up a dialog box with
various timesaving options. The code behind the form has several Form.Hide
commands for the cancel button, escape key etc.

The strange thing is that when multiple documents are open and this form
opens or closes, the active document changes randomly between the one that
was intended to be printed and one of the others that is open.

The only workaround I've found is to change all occurences of 'Form.Hide' to
'End' in the form's code.

Is this acceptable practice, or is there a better way?

Thanks,

Iain
 
J

Jezebel

Using End is TERRIBLE practice. It is included in VBA only for backwards
compatability with antedeluvian versions of basic. VBA code expects to
terminate in an 'orderly fashion' meaning that all the 'unload' and
'terminate' functions get called in due sequence. 'End' just stops your code
in its tracks: it's equivalent to shutting down your computer by pulling the
power lead.

On top of which, it won't reliably solve your problem anyway. There is a
known 'issue' with VBA and ActiveDocument -- exactly as you describe, the
document that is 'active' sometimes changes unpredictably.

The better approach is to set a variable to point to the document you are
interested in, and work with that --

Dim pDoc as Word.Document
Set pDoc = ActiveDocument

Then pass pDoc as an argument to all the code that currently does things
with ActiveDocument, and use the argument instead --

--- calling function ---
PrintDoc1 Doc:=pDoc


--- called function ---
Sub PrintDoc (Doc as Word.Document)
:
Doc.Print



Separately, if your forms are being hidden, there should also be code
somewhere that unloads them.
 
I

Iain McLaren

A further thought... The 'document switching' problem is occuring long
before ActiveDocument is being used - basically as soon as the form loads.
Remove the Form.Hide statements from the form's code and the problem *seems*
to go away!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top