从Word文档表中填充Excel文件-VBA

时间:2019-02-13 13:16:45

标签: excel vba ms-word

我对VBA还是很陌生,并试图根据Word Documents填充一个预先存在的Excel文档。

Word文档将具有三个表,并且某些单元格将成为Excel列。这个想法是,每天都会有新的产品信息表出现,并且需要在Excel表后附加。我首先查看了this先前提出的问题。我是否要创建一个启用宏的Excel工作表并在Excel中运行它?我可以让宏在Word文档的目录中查找并执行迭代宏吗?

2 个答案:

答案 0 :(得分:1)

那是最简单的解决方案。在Excel中,使用“工具”,“引用”在VB编辑器中设置对Word的引用-然后可以编写代码以在Excel中操作Word。您可以使用关键字DIR在文件夹中查找文件,然后声明Word对象,打开Word文档,遍历文档中的表,然后将值复制到Excel中的正确单元格中。只需注意Word粘贴在单元格中的^ p字符-我倾向于将单词单元格的内容放入字符串变量中,然后将Left(s,len(s)-1)放入excel以删除最后一个字符。

答案 1 :(得分:1)

怎么样?

Sub ImportFromWord()

Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document

Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True

Set wrdDoc = wrdApp.Documents.Open(ThisWorkbook.Path & "\My document.doc")
'Use below line if document is already open.
'Set wrdDoc = Documents("My document.doc")

With wrdDoc

    N_Of_tbles = .Tables.Count

    If N_Of_tbles = 0 Then
        MsgBox "There are no tables in word document"
    End If

    Set wrdTbl = .Tables(1)

    ColCount = wrdTbl.Columns.Count
    RowCount = wrdTbl.Rows.Count


    ' Loop through each row of the table
    For i = 1 To RowCount
        'Loop through each column of that row
        For j = 1 To ColCount
            'This gives you the cell contents
            Worksheets("sheet1").Cells(i, j) = wrdTbl.Cell(i, j).Range.Text
        Next j
    Next i
End With

Set wrdDoc = Nothing
Set wrdApp = Nothing

MsgBox "completed"

End Sub