Word文档仅在文档中提取表格

时间:2012-11-28 10:23:32

标签: excel excel-vba ms-word vba

我正在使用此代码。它打开一个Word文档从文档中提取表格并填充Excel文件。一切都很适合这部分。 现在我只想在word表的第一个单元格包含这个字符串“Row N#”并且我被阻止时填充Excel文件。

这是我的代码:

    Option Explicit

    Sub ImportWordTable()

    Dim wdDoc As Object
    Dim wdFileName As Variant
    Dim tableNo As Integer 'table number in Word

    Dim iRow As Long 'row index in Excel

    Dim iCol As Integer 'column index in Excel

    Dim resultRow As Long
    Dim tableStart As Integer
    Dim tableTot As Integer

    On Error Resume Next

    ActiveSheet.Range("A:AZ").ClearContents

    wdFileName = Application.GetOpenFilename("Word files (*.doc),*.doc", , _
    "Browse for file containing table to be imported")

    If wdFileName = False Then Exit Sub '(user cancelled import file browser)

    Set wdDoc = GetObject(wdFileName) 'open Word file

    With wdDoc
        tableNo = wdDoc.tables.Count
        tableTot = wdDoc.tables.Count
         If tableNo = 0 Then
           MsgBox "This document contains no tables", _
           vbExclamation, "Import Word Table"
        ElseIf tableNo > 1 Then
            tableNo = InputBox("This Word document contains " & tableNo & " tables." & vbCrLf & _
        "Enter the table to start from", "Import Word Table", "1")
    End If

    resultRow = 4

    For tableStart = 1 To tableTot
        With .tables(tableStart)
            If .tables(tableStart).Cell(1, 1).Range.Value = "Row N#" Then
            'copy cell contents from Word table cells to Excel cells

                For iRow = 1 To .Rows.Count
                    For iCol = 1 To .Columns.Count
                            Cells(resultRow, iCol) = WorksheetFunction.Clean(.Cell(iRow, iCol).Range.Text)
                    Next iCol
                    resultRow = resultRow + 1
                Next iRow
           End If
        End With
        resultRow = resultRow + 1
    Next tableStart
End With

End Sub

1 个答案:

答案 0 :(得分:0)

End With的{​​{1}}在哪里?

我认为你真的不想找wdDoc这是第n个表第n个子表的第一个单元格 - 丢失wdDoc.tables(tableStart).tables(tableStart).Cell(1, 1).Range.Value

之一

.tables(tableStart).语句似乎是一个好主意,但它们让你对这种错误持开放态度,特别是当它们被嵌套时。更可读,更不容易定义本地表变量并在循环开始时分配给它。

此外,我认为通过利用剪切和粘贴功能可以更快更容易地实现这一目标