2012-06-22 71 views
1

我有一个word文档包含html标签定义的许多html文档。我想创建一个数组或范围集合,每个范围包含一个html文档。例如,这里是Word文档:Word文档迭代使用VBA

<html> <head> <title> </title> </head> <body> HTML Doc 1 </body> </html> 
<html> <head> <title> </title> </head> <body> HTML Doc 2 </body> </html> 
<html> <head> <title> </title> </head> <body> HTML Doc 3 </body> </html> 

等我想填充rngHTMLDocs()作为范围具有一系列范围,其中包含每个开口内的文本和关闭的HTML标记的每个范围。

我已经创建了下面的代码,试图遍历定义这些范围的整个文档,但它只是继续选择HTML文档1。我想我可能会以错误的方式接近整个迭代的事情。总之,这里是代码:

Set rngDocContent = ActiveDocument.Content 
intCounter = 1 
With rngDocContent.Find 
    .ClearFormatting 
    .Text = "<html>" 
    .Replacement.Text = "" 
    .Forward = True 
    .Wrap = wdFindContinue 
    .Execute 
    Do While .Found = True 
     Set rngTemp = rngDocContent.Duplicate 
     rngTemp.Select 
     Selection.Extend 
     With Selection.Find 
      .ClearFormatting 
      .Text = "</html>" 
      .Replacement.Text = "" 
      .Forward = True 
      .Wrap = wdFindAsk 
      .Execute 
     End With 
     Set rngHtmlDocs(intCounter) = Selection.Range 
     Selection.Start = Selection.End 
     intCounter = intCounter + 1 
    Loop 
End With 

在设定rngDocContent整个文档,并使用wdFindContinue,我希望它实际上还在继续寻找一个打开HTML标记的下一个实例文档,但事实并非如此。预先感谢您提供的任何帮助。

回答

1

找出我缺少的是Loop语句之前的.Execute语句,因为这是导致原始.Find继续的原因。我还添加了ReDim Preserve语句,因为我没有事先计算文档中包含多少HTML文档。所以现在循环的结尾看起来像这样:

 Set rngHtmlDocs(intCounter) = Selection.Range 
     Selection.Start = Selection.End 
     intCounter = intCounter + 1 
     ReDim Preserve rngHtmlDocs(intCounter) 
     .Execute 
    Loop 
End With 

希望这有助于某人。

1

在这种情况下,范围对象的集合会更适合您吗?创建一个集合对象,并且每次迭代搜索时,都会创建一个新的范围对象,然后将其添加到集合中。这样每个html文档都可以被引用为colRanges(n)?

+0

一个集合会比数组提供任何优势吗? –

+0

这取决于你想如何去做你的循环代码,以及你在得到它之后对范围做了什么。您也不必担心重新调整阵列变量,如果需要,您可以直接从集合中使用范围。如果你有一个集合,你可以通过类似'对于colRanges中的每个varObj来执行你的循环; I = I + 1; set varObj = colRanges(i); {做其他代码}; next'。如果你有什么作品,太棒了。就我个人而言,当处理诸如范围之类的对象时,我发现使用集合eaiser。 – KFleschner