0

我正在构建一个用户表单(在 Excel 中),它为用户提供了 Excel 到 Word 自动化的以下选项:

所有这些选项都受到这篇 Microsoft 文章的启发。

  • 自动/手动更新链接/断开链接(\a 开关)
  • 存储图形数据(\d 开关)
  • 插入为位图(\b 开关)
  • 作为图片插入(\p 开关)
  • 保持源文件的格式(\f 4 开关)
  • 匹配目标文档的格式(\f 5 开关)
  • 作为 HTML 插入(\h 开关)
  • 插入为 RTF(\r 开关)
  • 以纯文本格式插入(\t 开关)
  • 插入为 Unicode 文本(\u 开关)
  • 更新后保留格式(* MERGEFORMAT 开关)

我知道我可以录制一个宏以将每个选项发送到 Word,然后解释结果,但是有谁知道我可以如何控制发送到 Word 的语法(可能作为内置字符串)而不是对上面的每个选项进行繁重的编码和研究?

另外,有谁知道哪些选项不能与哪个选项一起使用?例如,我不能作为位图和图片发送。

我要发送的语法是:

{ LINK ClassName "FileName" [PlaceReference ] [Switches ] }

例如:

{ LINK Excel.Sheet.8 "C:\\My Documents\\Profits.xls" "Sheet1!R1C1:R4C4" \a \p }

任何建议或帮助将不胜感激。

谢谢。

R

4

1 回答 1

0

是的,您可以使用“内置字符串”。这可能是最简单的方法。

在 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!RangeInRCFormatrangename。您可能需要 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
于 2020-07-24T17:38:39.770 回答