Word Interop Not Working In A Scheduled Task

2020-05-27 08:16发布

I'm currently developing a script that takes a Word document, opens it up in Word, and then prints the Word file as a PDF. Everything works great when run manually either on my machine or the server. The problem comes in when I attempt to run it as a scheduled task.

One of the requirements is that this should be done nightly without any intervention. When I set up a schedule task to do this and set the security options to "Run only when user is logged on" everything works fine. Problem is, this has to be run with or without someone being logged on. If I set the task to "Run whether user is logged on or not", the script fails on the following line:

wordDoc = MSWord.Documents.Open(ref fileToConvert, ref refFalse, ref refTrue, 
                                ref RN, ref RN, ref RN, ref RN, ref RN,
                                ref RN, ref RN, ref RN, ref RN, ref RN,
                                ref RN, ref RN, ref RN);

MSWord.Documents.Open() works, but returns null.

This task is running on Windows Server 2008 with Office 2007.

Is there another approach I should be taking for this?

2条回答
够拽才男人
2楼-- · 2020-05-27 08:23

I believe that many people have tried to do something close to what you are attempting and failed. There is a lot of chatter about not being able to run any office interop based solutions in a server-like mode (unattended etc).

See here and here

I know this is probably not the answer you were looking for but it is nevertheless how it is!

查看更多
Juvenile、少年°
3楼-- · 2020-05-27 08:25

I've had problems automating Office from a Windows Service under Windows Server 2008, even though that works fine under Windows Server 2003. The problem also occurs at the Open call, though it actually raises an exception rather than simply returning null. Anyway, you might want to try this...

I tried following the advice given by H Ogawa in this MSDN thread, and it seemed to work. It's bizarre, but kudos to Mr. Ogawa for discovering it.

Summary of the 'Ogawa Hack': create a desktop folder for the system profile, as either

C:\Windows\SysWOW64\config\systemprofile\Desktop, or

C:\Windows\System32\config\systemprofile\Desktop

...depending on whether you have 64-bit Windows.

Also, the folder needs write permission for whatever user is "driving" Office.

[Edit: corrected link URL]

查看更多
登录 后发表回答