Microsoft Word中的拼写错误

For*_*oop 5 dom ms-word ms-office word-vba

我正在使用Microsoft Word中的拼写错误.只有少数拼写错误,访问SpellingErrors集合会变得缓慢(至少使用For/Next或For/Each循环).

有没有办法快速进入列表(复制,复制条目,停止集合的动态性质)?我只需要一个列表,快照一下,并且不需要动态或实时.

Tod*_*ain 5

这是我如何模拟创建和检查拼写错误:

Sub GetSpellingErrors()
    ''# Turn off auto-spellchecking
    Application.Options.CheckSpellingAsYouType = False
    ''# Set document
    Dim d As Document
    Set d = ActiveDocument
    ''# Insert misspelled text
    d.Range.Text = "I wantedd to beet hym uup to rite some rongs."
    ''# Get spelling errors
    Dim spellErrs As ProofreadingErrors
    Set spellErrs = d.SpellingErrors
    ''# Dump spelling errors to Immediate window
    For spellErr = 1 To spellErrs.Count
        Debug.Print spellErrs(spellErr).Text
    Next
    ''# Turn back auto-spellchecking
    Application.Options.CheckSpellingAsYouType = True
End Sub
Run Code Online (Sandbox Code Playgroud)

在我这边测试这个在Word 2003和Word 2010中运行得非常快.请注意,这将给你六个拼写错误,而不是四个.虽然"beet"和"rite"是英文单词,但在这句话中它们被认为是"拼写错误".

请注意Application.Options.CheckSpellingAsYouType = False.这将关闭自动拼写错误检测(红色波浪形).这是一个应用程序范围的设置 - 不仅仅是针对单个文档 - 所以最好的做法是将其重新打开,如果这是最终用户在Word中所期望的,就像我最后所做的那样.

现在,如果在Word 2007/2010中启用了检测(这不适用于2003及更早版本),则只需读取XML中的拼写错误的单词(WordprocessingML)即可.这个解决方案设置和管理起来比较复杂,而且只有在你不使用VBA编程而是使用Open XML时才应该使用.使用Linq-to-XML的简单查询就足以获得所有拼写错误的单词的IEnumerable.您可以在元素的.Value每个属性w:type="spellStart"w:type="spellEnd"属性之间转储所有XML <w:proofErr/>.上面生成的文档在WordprocessingML中有这一段:

<w:p w:rsidR="00A357E4" w:rsidRDefault="0008442E">
  <w:r>
    <w:t xml:space="preserve">I </w:t>
  </w:r>
  <w:proofErr w:type="spellStart"/>
  <w:r>
    <w:t>wa</w:t>
  </w:r>
  <w:bookmarkStart w:id="0" w:name="_GoBack"/>
  <w:bookmarkEnd w:id="0"/>
  <w:r>
    <w:t>ntedd</w:t>
  </w:r>
  <w:proofErr w:type="spellEnd"/>
  <w:r>
    <w:t xml:space="preserve"> to </w:t>
  </w:r>
  <w:proofErr w:type="spellStart"/>
  <w:r w:rsidR="003F2F98">
    <w:t>b</w:t>
  </w:r>
  <w:r w:rsidR="005D3127">
    <w:t>eet</w:t>
  </w:r>
  <w:proofErr w:type="spellEnd"/>
  <w:r w:rsidR="005D3127">
    <w:t xml:space="preserve"> </w:t>
  </w:r>
  <w:proofErr w:type="spellStart"/>
  <w:r w:rsidR="005D3127">
    <w:t>hym</w:t>
  </w:r>
  <w:proofErr w:type="spellEnd"/>
  <w:r w:rsidR="005D3127">
    <w:t xml:space="preserve"> </w:t>
  </w:r>
  <w:proofErr w:type="spellStart"/>
  <w:r w:rsidR="005D3127">
    <w:t>uup</w:t>
  </w:r>
  <w:proofErr w:type="spellEnd"/>
  <w:r w:rsidR="005D3127">
    <w:t xml:space="preserve"> to </w:t>
  </w:r>
  <w:proofErr w:type="spellStart"/>
  <w:r w:rsidR="005D3127">
    <w:t>rite</w:t>
  </w:r>
  <w:proofErr w:type="spellEnd"/>
  <w:r w:rsidR="005D3127">
    <w:t xml:space="preserve"> some </w:t>
  </w:r>
  <w:proofErr w:type="spellStart"/>
  <w:r w:rsidR="005D3127">
    <w:t>rongs</w:t>
  </w:r>
  <w:proofErr w:type="spellEnd"/>
  <w:r w:rsidR="005D3127">
    <w:t xml:space="preserve">. </w:t>
  </w:r>
</w:p>
Run Code Online (Sandbox Code Playgroud)