在Excel中,我有一个userform,它使用RowSource = myTable从Excel表中填充ListBox。
现在我想选择一行,按一个按钮,然后将所选行中的每一列导出到Word文档的不同位置,这是一个带有预先格式化文本的模板。 Column1应该将place1,column2转到place2,无论我想要什么......
Word中有哪些数据目标/占位符可用于插入数据?
答案 0 :(得分:0)
Word有多种可能性让开发人员编写将在文档中显示的数据。使用哪个取决于开发人员的个人要求。
Bookmark
对象提供Range
属性,以便可以格式化或以其他方式操纵插入的内容。书签可以在文档的其他位置引用作为交叉引用或多次重复信息。要写入书签的VBA代码
ActiveDocument.Bookmarks("BookmarkName").Range.Text = "Data as string"
使用内容书写书签会删除书签。如果书签应该保留
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
Document.Variable
或CustomDocumentProperty
字段将文字内容写入DocVariable
或DocProperty
个对象,并将内容反映在文档表面上。这具有内容与文档一起旅行的优点,无论用户是否编辑表面上显示的内容。格式化内容存在问题。要写入文档变量和自定义文档属性:
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"
由于内容控件可以具有相同的标题或标记,因此对象模型会返回这些属性的数组。 Word还为每个内容控件分配一个唯一ID(GUID) - 如果GUID已知,则可以直接寻址内容控件。
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
以下代码段演示了如何循环文档中未链接到邮件合并数据源的所有字段,搜索合并字段并将其替换为数据
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
简单搜索代码:
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