Excel VBA从Word中的Found文本中获取页码

时间:2016-08-15 18:16:52

标签: excel vba excel-vba macros

我是VBA的新手,我正在尝试在Excel中组合一个宏。该宏用于在Word文档中搜索特定的文本字符串并返回其所在的页码(即该列将说明" ###在文档的页面#上找到")。

我似乎非常接近我想要的东西。宏找到文本,我可以告诉我它发现/没有找到它。但是,当我用代码运行它来返回页码时,它告诉我索引超出范围。我确信困难在于我对物体及其属性的有限理解。

感谢任何帮助!

    Sub OpenWordDoc()
       Set wordapp = CreateObject("word.Application")
         wordapp.Visible = True
         wordapp.Activate
         wordapp.Documents.Open "filename.docx"
         Set findRange = Sheet1.Range("D4:D8")
         For Each findCell In findRange.Cells
           Set rngFound = wordapp.ActiveDocument.Range.Find
           rngFound.Text = findCell.Value
           rngFound.Execute
           If rngFound.Found Then
              findCell.Offset(columnOffset:=1) =  rngFound.Parent.Information(wdActiveEndPageNumber)
           Else
              findCell.Offset(columnOffset:=1) = findCell.Value
           End If
        Next findCell
     wordapp.Quit
     Set wordapp = Nothing
    End Sub

编辑1:我在一台完全不同的计算机和不同版本的Word和Excel上试过这个。弹出相同的消息。错误就是这个 - rngFound.Parent.Information(wdActiveEndPageNumber) - 我认为rngFound.Parent不是"选择"。我还尝试用wdNumberOfPagesInDocument替换wdActiveEndPageNumber只是为了查看它是否是特定值并得到相同的错误消息。

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

Sub OpenWordDoc()
    Dim wordapp As Word.Application
    Dim findRange As Excel.Range
    Dim findCell As Excel.Range
    Dim rngFound As Word.Range

    Set wordapp = CreateObject("word.Application")
    wordapp.Visible = True
    wordapp.Activate
    wordapp.Documents.Open "filename.docx"
    Set findRange = Sheet1.Range("D4:D8")
    For Each findCell In findRange.Cells
        Set rngFound = wordapp.ActiveDocument.Range
        With rngFound.Find
            .Text = findCell.Value
            .Execute
        End With
        If rngFound.Find.Found Then
            findCell.Offset(columnOffset:=1) = rngFound.Information(wdActiveEndPageNumber)
        Else
            findCell.Offset(columnOffset:=1) = findCell.Value
        End If
    Next findCell
    wordapp.Quit

    Set rngFound = Nothing
    Set findCell = Nothing
    Set findRange = Nothing
    Set wordapp = Nothing
End Sub

希望有所帮助

相关问题