MS Word:获取插入符号的实际 ASCII 码

MS Word: Getting the actual ASCII code of an inserted symbol

我正在尝试为 MS-Word 编写 VBA 代码,以从 table 中删除带有未勾选符号的行。 为此,我需要 MS-Word 识别它并将它与打勾的符号区分开来。但与 Excel 不同的是,MS-Word 似乎不擅长它。

关注问题,我插入了符号,但是我无法获取刚刚插入的字符的正确ASCII码。

这是我尝试过的:

Sub SymbolsTest()
    Selection.InsertSymbol 163, "Wingdings 2", True 'Insert unticked
    Selection.MoveRight Unit:=wdCharacter, Count:=-1, Extend:=wdExtend 'Select it
    Debug.Print AscW(Selection.Text) & "  " & Selection.Text 'Ask for ASCII
    Selection.Collapse 0
    Selection.InsertSymbol 82, "Wingdings 2", True 'Insert ticked
    Selection.MoveRight Unit:=wdCharacter, Count:=-1, Extend:=wdExtend 'Select it
    Debug.Print AscW(Selection.Text) & "  " & Selection.Text 'Ask for ASCII
End Sub

输出为:

40  (
40  (

我希望它是:

163  ?
82  ?

我也试过 ?Selection.Characters(1) = Selection.Characters(2) 立即 window 同时选择它们,我得到了 True

如有任何帮助,我们将不胜感激。

据我所知

  • 没有简单的方法可以直接使用 Selection 或 Range 的任何属性获取字符的代码点或字体名称

  • 在这种情况下,Word 始终使用代码点 40 (")"),并且在内部,它确实存储了您指定的字体名称和 Unicode 代码点(例如 U+F052对于选中的框)。

您可以做两件事。如果字符不是 40,则假设它已经具有正确的代码点(尽管我不确定)。但如果没有,

  • 检索选择或范围的 .XML 或 .WordOpenXML 并查找相关元素,例如><w:sym w:font="Wingdings 2" w:char="F052"/> 在 old-style .XML 和较新的 .WordOpenXML 中。您可以搜索文本 <w:sym 并在以下文本中查找字体和代码点,或者使用 XML 解析器“正确执行”。在这种情况下,知道 F052 表示“具有代码点 F052 的 Unicode 字符,或者表示”它是 F000 + 原始字符集中的代码点”,即本例中的 Wingdings 2 可能会很有用.

例如一种方法是在 VB 编辑器的 Tools-References 中引用 Microsoft XML 库(在本例中为 6.0)并使用以下代码:

Sub getCharFontAndCodepoint()
Dim xdoc As MSXML2.DOMDocument60
Dim xSymNodes As MSXML2.IXMLDOMNodeList
Set xdoc = New MSXML2.DOMDocument60
xdoc.async = False
If xdoc.LoadXML(Selection.XML) Then
  xdoc.SetProperty _
    "SelectionNamespaces", _
    "xmlns:w='http://schemas.microsoft.com/office/word/2003/wordml'"
  Set xSymNodes = xdoc.SelectNodes("//w:sym/@w:font")
  If xSymNodes.Length > 0 Then
    Debug.Print xSymNodes(0).NodeValue
  End If
  Set xSymNodes = xdoc.SelectNodes("//w:sym/@w:char")
  If xSymNodes.Length > 0 Then
    Debug.Print xSymNodes(0).NodeValue
  End If
End If
Set xSymNodes = Nothing
Set xdoc = Nothing
End Sub
  • 或者,如果您只需要代码点,请复制字符并使用特殊粘贴使用 Unformatted Unicode Text 格式粘贴它,例如

     Selection.Copy
     Selection.PasteSpecial link:=False, DataType:=22 ' There does not seem to be a named enum for this particular format
     Selection.MoveLeft Unit:=WdUnits.wdCharacter, Count:=1, Extend:=WdMovementType.wdExtend
     Debug.Print Hex(AscW(Selection))
     Selection.Document.Undo