识别无效字符

时间:2018-02-06 12:00:18

标签: vba ms-word

我需要遍历word文档的每个字母,并将每个字母与有效字符列表进行比较。如果当前字符不在列表中,则应更改其字体颜色。

我是VBA的新手并编写了一个小的循环代码,但即使是一个小的word文件也需要很长时间。代码如下 -

Sub LoopThruFile()
Dim doc As Document
Dim CurrChar As String

Application.ScreenUpdating = False

Set doc = ActiveDocument

For i = 1 To doc.Range.Characters.Count
    CurrChar = doc.Range.Characters(i)
    If InStr("01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.-_()/@:&\%", CurrChar) = 0 Then
        doc.Range.Characters(i).Font.ColorIndex = wdRed
    End If
Next

Application.ScreenUpdating = True
End Sub

有更好更快的代码吗?

2 个答案:

答案 0 :(得分:1)

循环个人角色很慢。在您的示例中,可以提高性能的一件事是减少直接针对Range工作的层次结构级别的数量:

Dim doc as Document
Dim docRange as Range
Dim CurrChar as String

Set doc = ActiveDocument
Set docRange = doc.Content

请注意,Document.Range实际上是一个需要两个参数的方法; Document.Content自动将整个Range作为属性返回,因此更正确。

然后,Character对象实际上是一个Range对象。 VBA必须转换您的代码行以包含Text属性,以便将CurrChar分配给String。可能没有太大的区别,但更正确,可能更快一点:

CurrChar = docRange.Characters(i).Text

如果从文档末尾开始到开头,有时循环可以更快:

For i = docRange.Characters.Count to 1 Step -1
  CurrChar = docRange.Characters(i).Text
  If InStr("01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.-_()/@:&\%", CurrChar) = 0 Then
    docRange.Characters(i).Font.ColorIndex = wdRed
  End If
Next

您也可以尝试使用For Each,这可能是此方案中最快的doc.Range.Characters(i),因为您保存了多个Dim CurrChar as Range For Each CurrChar in docRange.Characters If InStr("01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.-_()/@:&\%", CurrChar.Text) = 0 Then CurrChar.Font.ColorIndex = wdRed End If Next 的调用,每个调用都消耗资源。

a value of type "const char *" cannot be assigned to an entity of type "LPCWSTR"

答案 1 :(得分:0)

以下对我有用。试试这个:

With ActiveDocument.Content.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .text = "[!abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0-9\,\.\-_\(\)\/\\\@\:\&\%]"
    .Replacement.text = ""
    .Replacement.Font.Color = wdColorRed
    .MatchWildcards = True
    .Execute Replace:=wdReplaceAll
End With