如何在 VBA 中设置 Selection.Start?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8702709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set Selection.Start in VBA?
提问by aurel
I have a problem with adjusting selection inside of a table. I have a function that goes through a document word by word to analyze it's contents looking for specific patterns. Unfortunately, in tables Char(7)
character breaks the selection - when it's selected, all cells become selected automatically. To work around this problem I store the proper Selection.Start
parameter.
我在调整表格内的选择时遇到问题。我有一个函数,可以逐字逐句浏览文档以分析其内容以寻找特定模式。不幸的是,在表格中Char(7)
字符会破坏选择 - 当它被选中时,所有单元格都会被自动选中。为了解决这个问题,我存储了正确的Selection.Start
参数。
Here is my code:
这是我的代码:
If InStr(Selection.text, Char(7)) > 0 Then
Selection.start = selStart
Selection.End = selStart + (Len(tekst) - 2)
End If
Well, it did not help. I can see, while debugging, that selStart
is 441 and Selection.Range.Start
is 427 (427 would be the beginning of the cell, when the word I'm looking for is on the position of 441). In the next step... Selection.Start
still is 427.
好吧,它没有帮助。我可以看到,在调试时,即selStart
441 和Selection.Range.Start
427(427 将是单元格的开头,当我要查找的单词位于 441 的位置时)。下一步……Selection.Start
还是427。
I've also tried another aproach using MoveStart
and MoveEnd
but no matter what I do, the Selection.Start
doesn't change.
我还尝试了另一种方法MoveStart
,MoveEnd
但无论我做什么,Selection.Start
都不会改变。
回答by aurel
Well of course! I can't move Selection.Start, while Chr(7) is in the selection! Everything works perfectly when I move Selection.End fisrt...
嗯,当然!我无法移动 Selection.Start,而 Chr(7) 在选择中!当我移动 Selection.End 时,一切正常...
If InStr(Selection.text, Chr(7)) > 0 Then
Selection.MoveEnd Unit:=wdCharacter, Count:=-1
Selection.start = selStart
End If
回答by chris neilsen
Maybe a different approach is in order: rather than manipulate the selection, iterate the Document.Words
collection. Something like:
也许需要采用不同的方法:而不是操作选择,而是迭代Document.Words
集合。就像是:
Sub PreccessAllWords()
Dim doc As Document
Dim wd As Range
Set doc = ActiveDocument
For Each wd In doc.Words
If wd.Text = "Foo " Then
wd.Text = "Bar "
End If
Next wd
End Sub