可以通过Word文档的每个页面优化宏循环来获取每个表吗?

时间:2015-01-22 18:50:08

标签: vba excel-vba foreach word-vba excel

我有一个Word文档,其中包含许多表格。

我需要将表导出到excel中,并在每行旁边添加一列以显示相应的Word页码。一旦准备好打印,这个excel文件将用于为我的Word文档制作索引。

我可以在excel文件中使用宏访问我的Word文件。我想遍历Word中的每个页面,然后遍历页面中的每个表格以复制到excel中。通过这种方式,我将知道我所在的页面,并且可以获得页码。

所以我想做这样的事情:

for each page in word
    for each table in this page
        copy the table into excel and also add the Word page number beside each row
    end
end

我尝试编写宏但它无法在页面中获取任何表格:

Set wdDoc = GetObject(wdFileName) 'open Word file

With wdDoc
    pagesTot = wdDoc.Pages.Count
    tableTot = wdDoc.Tables.Count

    resultRow = 4

    For tableStart = 1 To tableTot
        With .Tables(tableStart)
            'copy cell contents from Word table cells to Excel cells
            For iRow = 1 To .Rows.Count
                For iCol = 1 To 2 'only need to copy first 2 columns from Word into Excel
                    'This does not get the Word page number
                    TblPage = .cell(iRow, iCol).Information(3)
                    'copy cells from Word to Excel
                    Cells(resultRow, iCol) = WorksheetFunction.Clean(.cell(iRow, iCol).Range.Text)
                    'put the Word page number beside the row in Excel
                    Cells(resultRow, iCol).Offset(0, 1).Value = TblPage
                Next iCol
                resultRow = resultRow + 1
            Next iRow
        End With
        resultRow = resultRow + 1
    Next tableStart
End With

但是,当我在页面循环中时,我似乎无法访问该页面中的表格。我尝试使用MsgBox来显示该页面中的表数,但它总是显示为0。

甚至可以访问页面中的表格?

非常感谢任何帮助,谢谢。

修改 我编辑了上面的代码,我越来越近了。 我遇到麻烦的唯一一条就是:

TblPage = .cell(iRow, iCol).Information(3)

我正在尝试使用该行从Word获取页码,但最终得到的页面编号为0。我再次在Excel中编写所有这些代码。

有没有人知道从Word获取页码的正确方法?

再次感谢。

1 个答案:

答案 0 :(得分:1)

您建议的逻辑非常接近您的需求。事实上,最好是遍历表并检查表的哪个页面(结束)。这是你需要的逻辑。

Sub GetPageNumberForTable()

    Dim TBL As Table
    Dim TblPage As Integer
    For Each TBL In ActiveDocument.Tables

        'this is value you need
        TblPage = TBL.Range.Information(wdActiveEndPageNumber)

        'test- check value in immediate window
        Debug.Print TblPage

        'your copy code here
        '.....
    Next

End Sub