如何在 vba 中为一组特定字符设置 Word 的范围?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27160825/
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 do I set a range for Word in vba for a specific set of characters?
提问by RaifMT
I am finding a starting and ending character within a Word paragraph, but for the life of me, cannot determine how to set a range that includes those characters. Here is an excerpt of what I have:
我在 Word 段落中找到一个开始和结束字符,但对于我的生活,无法确定如何设置包含这些字符的范围。这是我所拥有的摘录:
Set rngTemp = w.Paragraphs(i).Range
For iCounter = 1 To rngTemp.Characters.Count
If rngTemp.Characters(iCounter).HighlightColorIndex = wdYellow Then
lStartPos = iCounter
While rngTemp.Characters(iCounter).HighlightColorIndex = wdYellow
iCounter = iCounter + 1
Wend
lEndPos = iCounter
Using the values for the starting and ending characters, how do I set a range that contains that string? I have made a number of attempts, but all unsuccessful.
使用开始和结束字符的值,如何设置包含该字符串的范围?我已经进行了多次尝试,但都没有成功。
The instruction on Microsoft's "Working with Ranges" page have the following code:
Microsoft 的“使用范围”页面上的说明包含以下代码:
Set rngDoc = ActiveDocument.Range(Start:=0, End:=10)
I receive no errors in the first line of my sample ("Set rngTemp ..."), which seems to be very comparable to Microsoft's sample. But when I try:
我在示例的第一行(“Set rngTemp ...”)中没有收到任何错误,这似乎与 Microsoft 的示例非常相似。但是当我尝试:
Set r = w.Paragraphs(i).Range(Start:=lStartPos, End:=lEndPos)
I get the "Compile Error: Wrong number of arguments or invalid property assignment"
我收到“编译错误:参数数量错误或属性分配无效”
采纳答案by RaifMT
I thought I had found the answer with this code:
我以为我已经用这段代码找到了答案:
Set r = w.Range(w.Paragraphs(i).Range.Characters(lStartPos).Start, _
w.Paragraphs(i).Range.Characters(lEndPos).End)
but it still produced an error. In the immediate window, I pasted the code from each line and the numbers showed up for each. Then I changed the set statement to use the actual numbers, and that worked. For some reason, VBA does not like to allow the numbers from the code immediately above to work in setting the range variable. I changed the original code (from the top) to this:
但它仍然产生了错误。在即时窗口中,我粘贴了每一行的代码,并显示了每一行的数字。然后我更改了 set 语句以使用实际数字,这奏效了。出于某种原因,VBA 不喜欢让上面代码中的数字在设置范围变量时起作用。我将原始代码(从顶部)更改为:
Set rngTemp = w.Paragraphs(i).Range
For iCounter = 1 To rngTemp.Characters.Count
If rngTemp.Characters(iCounter).HighlightColorIndex = wdYellow Then
'lStartPos = iCounter
lStartPos = w.Paragraphs(i).Range.Characters(iCounter).Start
While rngTemp.Characters(iCounter).HighlightColorIndex = wdYellow
iCounter = iCounter + 1
Wend
'lEndPos = iCounter
lEndPos = w.Paragraphs(i).Range.Characters(iCounter).End
Set r = w.Range(lStartPos, lEndPos)
and it worked.
它奏效了。