是的,您可以使用“内置字符串”。这可能是最简单的方法。
在 Word 中插入字段的最安全方法是插入“空”字段,即具有类型wdFieldEmpty
而不是特定类型wdFieldLink
的字段,但提供字段的完整文本。然后更新它(我不记得细节,所以我倾向于尝试看看是否有必要)。
例如,假设你有一个在 word 文档中Word.Range
调用的对象的引用rng
,并且你有对 Word 对象库的引用,你可能会使用这样的东西:
Dim fld As Word.Field
Dim fldText As String
fldText = "LINK Excel.Sheet.12 ""C:\\test\\xl sources\\Book1.xlsx"" ""Sheet1!R3C1:R5C3"" \a \f 4 \r"
' "False" = don't insert \*Mergeformat
Set fld = rng.Fields.Add(rng, Word.wdFieldType.wdFieldEmpty, fldtext, False)
fld.Update
如果您没有引用 Word 对象库,则可以使用
Dim fld As Object
Dim fldText As String
fldText = "LINK Excel.Sheet.12 ""C:\\test\\xl sources\\Book1.xlsx"" ""Sheet1!R3C1:R5C3"" \a \f 4 \r"
Set fld = rng.Fields.Add(rng, -1, fldtext, False)
fld.Update
需要考虑的一些事项:
- 在 .docx 格式中,只有某些特殊粘贴格式会在文档中插入域代码。其他人将插入链接对象。因此插入 { LINK } 字段不一定会与执行选择性粘贴的用户具有完全相同的效果
- COM ProgId(Excel.Sheet.12 不需要引用,但您确实需要使用正确的 ProgId
- 如果路径/文件名包含空格等特殊字符,则可能需要用引号引起来,并且需要将反斜杠加倍
- “子集”(在我的示例中,
Sheet1!R3C1:R5C3
应该是sheetname!RangeInRCFormat
或rangename
。您可能需要 sheetname!rangename 用于具有工作表范围而不是工作簿范围且不在第一个工作表中的范围。
- 您不能保证您提供给 Word 的任何字符串都将在字段更新后继续存在。Word 可以用它自己的链接表示形式替换 LINK 代码。事实上,Word 以您希望的方式解释 COM LINK 字符串可以说是一个好处。
至于“你可以用什么”
\a switch - it's either \a or not \a. You can't insert *and* break the link using the field
\d switch - Off the top of my head, I'm not sure what \d does these days. You probably can't avoid storing graphical data in .docx
\b, \p (basically a Word wmf/emf format file, \h, \r, \t, \u are mutually exclusive
\f - you can only have one \f option ( e.g. your 4 or 5)
\*Mergeformat tries to preserve the formatting used when you last inserted, and/or that you applied after that. But for complex formatting such as a table layout, you will need to discover whether it does what you need or not.
如果您需要更新Word 中已有的LINK 字段,只要您能找到该字段,例如您知道它是文档中的 3rs 字段,您应该可以替换其字段代码并再次更新该字段,例如
'Let's say the variable doc contains a reference to the Word Document
Dim newFldText As String
newFldText = "LINK Excel.Sheet.12 ""C:\\test\\xl sources\\Book1.xlsx"" ""Sheet1!R3C1:R5C3"" \a \f 4 \r \*MergeFormat"
With doc.Fields(3)
.Code.Text = newFldText
.Update
End With