How to create a Word application RRS feed

  • General discussion

  • Hi there,

    Until last week, I used to create Word applications using On-Error-Resume-Next or Try-Catch blocks. For example, in VSTO I used something like this:

          wdApp = CType(GetObject(, "Word.Application"), Word.Application)
        Catch ex As System.Exception
          wdApp = CType(CreateObject("Word.Application"), Word.Application)
        End Try
    I never liked this approach because it produces an error if no Word application is available. Although this doesn't look like a problem, for me it is one, since I get more exceptions while debugging. The latter can be quite a difficult task and don't want to make it unnecessarily complex.

    After a long time, I discovered the Process class, which can detect if a Word application is already running. Using this class and a little of LINQ, you can produce the same result as above without causing an exception. My new code loooks like this:

        ' Search for Word applications in the local machine (local machine = ".").
        Dim runningProcs As Process() = Process.GetProcesses(".")
        Dim wordProcs As IEnumerable(Of Process) = From p As Process In runningProcs _
                              Where p.ProcessName = "WINWORD" _
                              Select p
        Dim wdApp As Word.Application
        If wordProcs.Count = 0 Then
          ' Create a new Word application.
          wdApp = CType(CreateObject("Word.Application"), Word.Application)
          ' Get an existing Word application.
          wdApp = CType(GetObject(, "Word.Application"), Word.Application)
        End If

    I found this useful class while reading Andrew Troelsen's Pro VB 2008 and the .NET 3.5 Platform.

    Hope you find this post useful!

    Carlos Mallen

    Tuesday, March 8, 2011 8:16 PM