At times, you may want to automate an Office application
but not require any user interaction with the Office application. In this case,
if the Office application displays a dialog box, your application appears to
stop responding until a user can dismiss the dialog box. However, a user who
can dismiss the dialog box may not be near the computer.
Office
applications are not designed for unattended execution. Therefore, an
application that automates Office may sometimes encounter a dialog box that is
displayed by the Office application. From normal testing of the application,
you can usually determine which dialog boxes occur, and you can write your code
to avoid those particular dialog boxes.
The following are some
recommended strategies for avoiding dialog boxes while you automate an Office
application:
- Determine if the property or method that you are using (the
one that is causing the dialog box) has optional arguments that you can pass to
it. Sometimes, by passing all arguments to the property or method, you can
avoid a dialog box. For example, if you are using the Open method to open an Excel workbook and that workbook is
password-protected, and you do not provide the Password argument when you call the Open method, Excel displays a dialog box that asks the user to enter
the password. To avoid the dialog box, provide a value for the Password argument when you call the Open method. Similarly, when you use the Close method to close a document, you can specify the SaveChanges argument to avoid a dialog box that asks the user to
save changes.For additional information on how to determine
the arguments that are available for the property or method that you are
calling, click the article number below to view the article in the Microsoft
Knowledge Base:
222101 HOWTO: Find and Use Office Object Model Documentation
- Study the object model of the Office application to see if
a property exists that prevents certain dialog boxes. For example, the Excel Application object has AskToUpdateLinks and AlertBeforeOverwriting properties.
- Set the Application.DisplayAlerts property (in Excel, Project, or Word) or use Application.DoCmd.SetWarnings False (in Access only) to turn off the display of alert messages. Most,
but not all, dialog boxes can be avoided by using this setting.
- Set the Application.FeatureInstall property (in Office 2000 and later) to handle possible This feature is not installed dialog boxes when you access a component that may not be
installed on the system.
- Use the On Error statement to avoid run-time error messages that may occur, such
as an error message that appears when you try to set Application.ActivePrinter when no printer driver is installed on the system.
- Test your application thoroughly to help anticipate when
dialog boxes may occur. For example, you may call the SaveAs method of an Office application to save to a file. If that file
already exists, a dialog box may appear and request confirmation to replace the
existing file. If you modify your code to check for the file before you call
the SaveAs method, you can prevent the dialog box from appearing. For
example, if the file already exists, you can delete it by using the Kill function before you call the SaveAs method.
NOTE: Even if you use these techniques and carefully design your
application to avoid dialog boxes, you may still be faced with a situation in
which a dialog box cannot be avoided with the methods and properties that are
exposed in the object model of the Office application. In such situations, it
may be necessary to programmatically dismiss a dialog box by simulating user
input. The following demonstration illustrates how to do this with a Visual
Basic .NET application.
Sample
The steps in this section demonstrate how to create a Visual
Basic .NET application to automate Word and print a document by using the
PrintOut method of the Word
Document object. If the default printer is configured to print to the FILE
port, a call to the
PrintOut method produces a dialog box that prompts the user to enter a
file name. To determine if the
PrintOut method causes this dialog box to appear, the Visual Basic .NET
application initializes a flag variable to False before it calls the
PrintOut method, then sets the flag to True after the
PrintOut method. Also prior to calling
PrintOut, a separate procedure is run on a new thread. That procedure
waits 5 seconds and checks the value of the flag variable. If the flag is True,
the procedure ends without taking further action. The document is printed and
the code execution continues beyond the
PrintOut method. However, if the procedure determines the flag variable is
still False, it is assumed that the
PrintOut method has not completed and that the delay is caused by a dialog
box that is waiting for user input. The procedure then gives focus to Word and
uses
SendKeys to dismiss the dialog box.
NOTE: For demonstration purposes, this sample uses the
PrintOut method in such a way that it displays a dialog box intentionally
when it prints to a printer that is set to a FILE port. Note that the
PrintOut method has two arguments,
OutputfileName and
PrintToFile, that you can provide to avoid this dialog box.
To
create the sample, follow these steps:
- Start Microsoft Visual Studio .NET. On the File menu, click New and then click Project. Under Project types click Visual Basic Projects, then click Windows Application under Templates. Form1 is created by default.
- On the View menu, click Toolbox to display the toolbox and add a button to Form1.
- Double-click Button1. The code window for the Form appears.
- In the code window, replace the following code
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub
with:
Private m_oWord As Object
Private m_sWordCaption As String
Private m_bMethodDone As Boolean
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
On Error GoTo ErrorHandler
'Create a new Word instance and put text in the new document.
m_oWord = CreateObject("Word.Application")
m_oWord.Visible = True
m_oWord.Documents.Add()
m_oWord.Selection.TypeText("Hello World!")
'Maximize the Word window so that if SendKeys is needed,
'keys will be sent to the Word window.
m_oWord.WindowState = 1 'wdWindowStateMaximize
'Obtain the Word caption for use with AppActivate.
m_sWordCaption = GetWordCaption()
'Initialize a flag to indicate the PrintOut method is not completed.
m_bMethodDone = False
'Start a new thread for calling the DismissDialog function, which
'checks the value of bMethodDone to see if the method completed.
Dim myThread As System.Threading.Thread
myThread = New System.Threading.Thread(AddressOf DismissDialog)
myThread.Start()
'Call the PrintOut method, which may prompt the user to select
'an output file name if the default printer is set to FILE.
m_oWord.PrintOut(Background:=False)
Done:
'Set a flag to indicate the method has completed.
m_bMethodDone = True
'Close the document and quit the Word instance.
On Error Resume Next
m_oWord.ActiveDocument.Close(SaveChanges:=False)
m_oWord.Quit()
m_oWord = Nothing
Exit Sub
ErrorHandler:
Resume Done
End Sub
Private Sub DismissDialog()
On Error Resume Next
Dim sKeys As String
'Pause for 5 seconds.
System.Threading.Thread.Sleep(5000)
'Determine if the PrintOut method is done.
If Not m_bMethodDone Then
'Make sure that Word has the focus before using SendKeys to it.
Microsoft.VisualBasic.Interaction.AppActivate(m_sWordCaption)
'Specify an output file name to create.
sKeys = "C:\MyOutput.prn"
'Delete the file if it already exists.
Microsoft.VisualBasic.FileSystem.Kill(sKeys)
'Send keystrokes to enter the output file name.
sKeys = sKeys & "~" '~ represents the Enter key to dismiss dialog
System.Windows.Forms.SendKeys.SendWait(sKeys)
End If
End Sub
Private Function GetWordCaption() As String
'This returns the caption of the Word window. For use with the
'AppActivate function.
Dim s As String
On Error Resume Next
s = m_oWord.ActiveWindow.Caption
If Err.Number = 0 Then 'no error
s = s & " - " & m_oWord.Caption
Else
s = m_oWord.Caption
End If
GetWordCaption = s
End Function
NOTE: The DismissDialog procedure creates a file at C:\MyOutput.prn. You can change this
in the code to a different file if desired. Also, you can customize the wait
time to be greater or less than five seconds when you use the Sleep method.
- On the Debug menu, click Start.
- Click Button1 on the form. This automates Word, adds a new document with some
text, and then sends it to the printer by using the PrintOut method. You do not see a dialog box if your printer is configured
to print to a printer.
- In Control Panel, change your default printer so that it is
configured to print to the FILE port.
- Click Button1 again and note that a dialog box appears in Word. Do not dismiss
the dialog box; wait five seconds and the dialog box is programmatically
dismissed. The C:\MyOutput.prn file is created.
Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs.
If you have limited programming experience, you may want to contact a Microsoft Certified Partner or Microsoft Advisory Services. For more information, visit these Microsoft Web sites:
Microsoft Certified Partners -
https://partner.microsoft.com/global/30000104Microsoft Advisory Services -
http://support.microsoft.com/gp/advisoryserviceFor more information about the support options that are available and about how to contact Microsoft, visit the following Microsoft Web site:
http://support.microsoft.com/default.aspx?scid=fh;EN-US;CNTACTMS