tags:

views:

979

answers:

1

Hi,

I'm editing a vb.net app for a mate and part of the requirements are to copy merge fields from one word document to another. I can copy them across using document.content.text but they come out as text (should've figured this i guess).

I think i've got them selected by:

Dim tDocFields As Microsoft.Office.Interop.Word.Fields
tDocFields = tDocument.Content.Fields

I'm then activating the doc i want to copy into and i think i need to then copy into that doc using the related word app.

vDocument.Activate()
vWord.Selection. ??? Insert() ???

Any pointers would be greatly appreciated... Am i on the right lines even?

A: 

You can access the available fields via the Fields collection however it has all the fields not just merge fields. You can easily identify merge fields but will have to do some basic parsing to extract the field name. The following code shows a messagebox with the contents of each merge field in a document:

Dim lo_field As Field
Dim lo_range As Range
Dim lo_fieldText As String

For Each lo_field In mo_doc.Fields
    If lo_field.Type = WdFieldType.wdFieldMergeField Then

        lo_range = lo_field.Code()

        lo_fieldText = lo_range.Text
        MsgBox(lo_fieldText)

    End If
Next

Once you've found each of the merge fields you can create new merge fields in the new document like so:

Imports Microsoft.Office.Interop.Word

Public Class Form1

    Dim mo_doc As Document
    Dim mo_missing As Object = System.Reflection.Missing.Value

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        ' Open word
        Dim lo_word As New Application
        lo_word.Visible = True

        ' Create a new word document
        mo_doc = lo_word.Documents.Add(mo_missing, mo_missing, mo_missing, mo_missing)
        mo_doc.Activate()

        ' Add a merge field
        mo_doc.Fields.Add(lo_word.Selection.Range, WdFieldType.wdFieldMergeField, "mergefieldname", True)

    End Sub
End Class

Hope this helps!

mdm
VB.NET has named and optional parameters, so you'd never need the mo_missing object when working with Word's object model!
Dennis Palmer