Word VBA提取数学及希腊字母上标时特殊符号显示为问号的问题问询
问题根因
VBA 内置的字符串类型默认以 ANSI 编码处理字符,∂这类属于 Unicode 区间的特殊符号直接通过字符对象赋值给字符串变量时,会因为编码不兼容被替换为?。
需新增/修改的逻辑
- 读取字符时不直接取默认返回值,改用
AscW函数读取字符的 Unicode 编码,再通过ChrW转换为可正常存储的 Unicode 字符串 - 移除原有代码中过滤
?的判断,避免正常识别的特殊符号被误拦截
修正后可正常捕获特殊符号的代码
Dim i As Long, j As String Dim txtboxString() As String Dim Superscript As String Dim myrange As Range Dim ap As Document: Set ap = ActiveDocument x = 0 For i = 1 To ap.Characters.Count j = "" If ActiveDocument.Characters(i).Font.Superscript = True Then Z = 0 ReDim Preserve txtboxString(x + 1) For Z = i To i - 5 Step -1 If Z > ap.Characters.Count Then GoTo 1 If ActiveDocument.Characters(Z) = "," Then GoTo 0 ' 改用Unicode方式读取字符,兼容特殊符号 If ActiveDocument.Characters(Z).Font.Superscript = True Then j = ChrW(AscW(ActiveDocument.Characters(Z))) & j Next Z End If 0: If j <> "" Then If j <> "," Then ' 移除原有的j<>"?"判断,避免正常符号被误删 txtboxString(x) = j x = x + 1 End If End If 1: If Z + 1 > ap.Characters.Count Then i = Z 'Else i = Z + 1 Set myrange = ActiveDocument.Characters(i + 1) myrange.MoveUntil Cset:="* " i = myrange.End - 1 Next
额外注意事项
如果后续需要将txtboxString数组的内容输出到外部文本文件,不要使用 VBA 原生的Open语句写入,需调用ADODB.Stream等支持 Unicode 编码的组件执行写入操作,否则导出的文件依然会出现乱码。
内容的提问来源于stack exchange,提问作者Andrew Melbourne
相关产品推荐
相关产品推荐

