Sub with ByRef to a Word.Application

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • asedt
    New Member
    • Jun 2008
    • 130

    Sub with ByRef to a Word.Application

    I have problem creating a private sub to replace text in a wordfile, is the use of ByRef good? The problem is that this works on my developing computer but not at the target computers.

    Code:
    Private Sub Replace(ByRef WordApp As Word.Application, ByVal OLDText As String, ByVal NEWText As String)
            WordApp.Selection.Find.ClearFormatting()
            WordApp.Selection.Find.Text = OLDText
            WordApp.Selection.Find.Replacement.ClearFormatting  ()
            WordApp.Selection.Find.Replacement.Text = NEWText
            WordApp.Selection.Find.Execute(Replace:=Word.WdRep  lace.wdReplaceAll, Forward:=True, Wrap:=Word.WdFindWrap.wdFindContinue)
        End Sub
    I get this error message during runtime:

    Code:
    System.NullReferenceException: Object reference not set to an instance of an object.
      at MyProg.Form1.Replace(Application& WordApp, String OLDText, String NEWText)
    Here is some source code where i create the word object, in my project i have added a reference to Microsoft Word 11 Object Libary, COM.

    Code:
    Dim WDApp As Word.Application
    WDApp = CreateObject("Word.Application")
    WDApp.Visible = False
    
    WDApp.Documents.Add(Template:="C:\template.dot", Visible:=False)
    
    Replace(WDApp, "<Replace ME>", "New Text")
    
    WDApp.Documents.Item(1).SaveAs("C:\newdoc.doc")
     
    WDApp.Quit()
    WDApp = Nothing
Working...