Exporting data from Excel to Word: data targets/placeholders

前端 未结 1 987
耶瑟儿~
耶瑟儿~ 2021-01-27 06:45

In Excel I have a userform that has a ListBox being populated from an Excel table using RowSource=myTable.

Now I want to select one line, press a button, and export eve

相关标签:
1条回答
  • 2021-01-27 07:22

    Word has multiple possibilities for the developer to write data that will be displayed in the document. Which to use depends on the individual requirement of the developer.

    1. Traditionally, bookmarks are most often used. A Bookmark object provides a Range property so that the inserted content can be formatted or otherwise manipulated. A bookmark can be referenced elsewhere in the document as a cross-reference or to repeat the information more than one time.

    VBA code to write to a bookmark

     ActiveDocument.Bookmarks("BookmarkName").Range.Text = "Data as string"
    

    Writing to a bookmark with content deletes the bookmark. If the bookmark should be retained

    Dim sBookmarkName as String
    Dim rngBookmark as Word.Range
    Dim doc as Word.Document
    Dim bkm as Word.Bookmark
    sBookmarkName = "BookmarkName"
    Set doc = ActiveDocument
    If doc.Bookmarks.Exists(sBookmarkName) Then
      Set bkm = doc.Bookmarks(sBookmarkName)
      Set rng = bkm.Range
      rng.Text = "Data as string"
      doc.Bookmarks.Add(sBookmarkName, rngBookmark)
    End If
    
    1. Text content can be written to Document.Variable or CustomDocumentProperty objects and the content reflected on the document surface by use of DocVariable or DocProperty fields. This has the advantage of the content travelling with the document, whether the user edits what's displayed on the surface, or not. Formatting the content is problematic.

    To write to document Variables and custom document properties:

    ActiveDocument.Variables("VariableName") = "Data as string"
    'See the language reference for more about values for Type
    ActiveDocument.CustomDocumentProperties.Add Name:="PropertyName", _
                                                LinkToContent:=False,  _
                                                Type:=msoPropertyTypeString, _
                                                Value:="Data as string"
    
    1. Starting in Word 2007, content controls are recommended by Microsoft as data placeholders. Programmatically addressing them is similar to working with bookmarks. Main differences:
      • the title or tag of a content control can be used more than once in the document
      • writing to a content control need not (but can) remove the content control (writing to a bookmark removes the bookmark, but it can be recreated if it's needed for referencing or writing data at a future time)
      • a content control can be linked to a Custom XML Part in the document
      • data written to content controls can be more easily extracted from the closed Word document, via the Office Open XML file format. (Even more easily if the content control is linked to a Custom XML Part)
      • Corollary: it's also possible to write data directly to a Custom XML Part that's linked to content controls in a document. This is especially interesting if the data should be written to a closed file.

    Since content controls can have the same title or tag, the object model returns an array for these properties. Word also assigns each content control a unique ID (GUID) - if the GUID is known, the content control can be addressed directly.

    Dim doc as Word.Document
    Dim sCC_ID as String
    Dim sCC_Title as String
    Dim sCC_Tag as String
    
    Set doc = ActiveDocument
    'ID value is passed as a string
    doc.ContentControls("1691881769").Range.Text = "Data as String"
    
    'Get the first content control with the given title
    sCC_Title = "Content Control Title"
    doc.ContentControls.SelectContentControlByTitle(sCC_Title).Item(1).Range.Text = "Data as String"
    
    'Loop all content controls having the same tag
    Dim aCC as Word.ContentControls
    Dim cc as Word.ContentControl
    
    sCC_Tag = "Content Control Tag"
    Set aCC = doc.SelectContentControlsByTag("Content Control Tag")
    For Each cc In aCC
        cc.Range.Text = "Data as string"
    Next
    
    1. It's possible to write data to merge fields, although this NOT how merge fields are meant to be used. This approach is most often used when the idea is that a user can set up a document "easily". Writing the code to target the merge fields is more complex than for the other types of placeholders.

    The following snippet demonstrates how to loop all fields in document not linked to a mail merge data source, search for the merge field and replace it with data

    Dim fld As Word.Field
    Dim fldRange As Word.Range
    Dim sFldCode As String, sDataField As String, sDataContent
    
    sDataField = "MergefieldName"
    sDataContent = "Data as string"
    For Each fld In ActiveDocument.Fields
        sFldCode = fld.code
        Select Case InStr(sFldCode, sDataField)
            Case Is > 0
              Set fldRange = fld.result
              fld.Delete
              fldRange = sDataContent
        End Select
    Next
    
    1. Find/Replace is also an option. Usually, some kind of special character delimits the start and end of the "placeholder". The code searches these characters, reads the placeholder and inserts data at the "found" position.

    Simple search code:

    Dim wdDoc As Word.Document
    Dim sPlaceholder as String, sData as String
    
    sData = "Data as string"
    sPlaceholder = "DataFieldName"
    Set wdDoc = ActiveDocument
    
    With wdDoc.content.Find
        .ClearFormatting
        .Text = "<<" & sPlaceholder & ">>"
        With .Replacement
            .ClearFormatting
            .Text = sData
        End With
        .Execute Replace:=wdReplaceAll
    End With
    
    0 讨论(0)
提交回复
热议问题