Excel宏:如何在循环到文档表而不是页面时获取单词标题

时间:2019-04-09 08:45:37

标签: excel vba

我有一个文档,该文档通过excel宏来获取word文档中的所有表,然后循环循环以获取数据并将其转换为excel。问题是我需要在循环进入表以将表数据与其员工相关联的同时,在每个页面的标题内提取数据(字符串)。

示例标头值:

第1页:“员工:简·莫茨”

第2页:“员工:简·莫茨”

第3页:“员工:克拉克·赖特”

第4页:“员工:Sam Molds”,等等。

样本表值:

Date  | No. of Tardy | No. of Undertime
11/12 |      5       |      10 

我可以成功将单词表数据导入excel,问题是我也需要这样的员工姓名:

所需的导入输出:

Name         |  Date  | No. of Tardy | No. of Undertime
Jane Motts   |  1/12  |      1       |      6 
Jane Motts   |  2/12  |      2       |      7 
Jane Motts   |  3/12  |      3       |      8 
Clark Wright |  1/12  |      4       |      6 
Sam Molds    |  2/12  |      7       |      7 
Sam Molds    |  3/12  |      8       |      8 

我的ImportWordTable宏如下:

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 (*.docx),*.docx", , _
"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", tableNo)
    End If

    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 .Columns.Count
                    Cells(resultRow, iCol) = WorksheetFunction.Clean(.cell(iRow, iCol).Range.Text)
                Next iCol
                resultRow = resultRow + 1
            Next iRow
        End With
        resultRow = resultRow + 1
    Next tableStart
End With

End Sub

0 个答案:

没有答案