问题在MS Word中选择特定数量的单词

时间:2014-08-28 19:27:21

标签: vba ms-word

我正在创建一个宏,从word文档中复制5000个单词并将其粘贴到新文档中:

Sub Excerpt_Selection()

Selection.MoveRight Unit:=wdWord, Count:=5000, Extend:=wdExtend 
Selection.Copy
Documents.Add.Activate
Selection.Paste

上面的代码工作正常,但是,它没有选择5000个单词,它选择大约4100个。我将从中获取单词的文档是一本书。关于如何让它精确选择5000个单词的任何想法?

谢谢!

1 个答案:

答案 0 :(得分:0)

Words方法和wdWord常量(因为它适用于Selection对象)也会将标点符号捕获为"字",所以&#34 ;你好,世界!"由4个字组成:"hello"", ""world""!"

Word不是我的专长,可能有一种比这更好的方法,这是一种蛮力:

Const punctuation as String = ",./?\:;" '<~~ Modify as needed with additional marks
Sub Excerpt_Selection()
Dim wCount as Long
Dim selectedWords as Range

Do

    Selection.MoveRight Unit:=wdWord, Count:=1, Extend:=wdExtend
    Set selectedWords = Selection.Range
    With selectedWords
        If InStr(1, punctuation, RTrim(.Words(.Words.Count))) = 0 Then wCount = wCount + 1
    End With
Loop While wCount < 5000

Selection.Copy
Documents.Add.Activate
Selection.Paste

End Sub
相关问题