Unexpected Document Exit when running a macro

E

esther.held

I use two documents based on the same template.

I run a certain macro to delete hidden text in the first
document. This works fine.

I switch to the second document and run the same macro.
Now, instead of deleting the hidden text, Word switches
back to the previous document. The hidden text deletion
is not carried out.
 
K

Klaus Linke

Hi Esther,

How do you switch between documents? The safe way to do it is to define
Document objects that refer to your files by name:

Dim docNew As Document
Dim docOld As Document
Set docNew = Documents("MyNew.Doc")
Set docOld = Documents("MyOld.Doc")
(assuming the two documents MyNew.Doc and MyOld.Doc are open already)

Then you can activate them and use ActiveDocument as before (docNew.Activate
: ActiveDocument.Tables(1).AllowAutoFit ...), or you can manipulate them
directly (For each tableLoop in docOld.Tables ...).

In Word2002/2003, I noticed that the focus switches to a different
window/document seemingly at random from time to time after you do a
replacement.
From the user interface, this is a real nuisance: Suddenly, another document
is active. The dialog box with the numbers of replacements is hidden behind
it, and it takes some time to sort things out.

I haven't figured out the cause yet, and didn't find the problem documented
in the MS Knowledge Base.
But if you run into such problems, I'd recommend to specify the document you
want to work on (docNew/docOld in the example above) explicitly all the
time, and avoid using "ActiveDocument".

Regards,
Klaus
 
E

Esther

Hi Klaus,

Thanks for your suggestions. However I do switch
documents manually (e.g. using CTREL+F6) and run the
macro in each document individually.

I am still trying to find out why the macro runs
perfectly in the first document but stalls when running
again in the second document.

Unfortunately, I have not been able to detect any
information in the TechNet.

Cheers,
Esther
 
K

Klaus Linke

Hi Esther,

Do you start the macro with a keyboard shortcut?

If you have a reproducible scenario, you could check whether the shortcut is
really assigned to the macro.
If you do Alt+Ctrl+Num+ (Alt-key + Ctrl + "+" on the numeric keypad) and
then use the keyboard shortcut, a dialog will show what that shortcut is
assigned to.
If the second document is attached to some template, the shortcut might be
assigned differently.

Or you might test if switching between documents with Alt+Esc or Alt+Tab
doesn't show the problem.

If you really want to get to the bottom of the problem, and the macro isn't
too long, you might post it here. Maybe it's something in the code that
switches the focus back to the first document. And others might try if they
can reproduce the problem.

It's not unlikely that there really is a bug. Word does seem to have a
problem telling which doc (or window?) has the focus in Word2002/2003.

Regards,
Klaus
 
Top