【问题标题】:Word Document Iteration Using VBA使用 VBA 进行 Word 文档迭代
【发布时间】:2012-06-25 20:55:45
【问题描述】:

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

<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() As Range,每个范围都包含每个开始和结束 html 标记中的文本。

我创建了以下代码,试图遍历定义这些范围的整个文档,但它只选择 HTML Doc 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 标记的下一个实例,但事实并非如此。提前感谢您提供的任何帮助。

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

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

    【讨论】:

    • 集合比数组有什么优势吗?
    • 这取决于你想如何处理你的循环代码,以及你在得到它之后对范围做了什么。您也不必担心重新调整数组变量,如果需要,您可以直接从集合中使用范围。如果您有一个集合,您可以通过执行类似For each varObj in colRanges; i=i+1; set varObj = colRanges(i); {do other code}; next 的操作来执行循环。如果你有什么作品,那就太好了。就个人而言,我发现在处理范围等对象时使用集合更容易。
    【解决方案2】:

    发现我缺少的是 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
    

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多