VBA:导出WORD表格到excel



我使用这段代码,以便导入excel的一些数据,并计算一行的总数,但我有一个"所需对象"错误时运行指向For周期。任何想法?

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 A As Integer
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
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 table number of table to import", "Import Word Table", "1")
End If



If TableNo = 1 Or TableNo = 2 Then

With .Tables(TableNo).Range.Copy

Range("A1").Activate
Application.CommandBars.ExecuteMso "PasteSourceFormatting"

'copy cell contents from Word table cells to Excel cells
For iRow = 1 To .Rows.Count
For iCol = 1 To .Columns.Count
Cells(iRow, iCol) = WorksheetFunction.Clean(.Cell(iRow, iCol).Range.Text)
Next iCol
Next iRow

A = "=SUM(C6:L6)"

InputBox ("Total" & A)
End With
End If
End With

使用以下代码作为起点示例。它使用早期绑定,但如果不是您想要的,它很容易更改。我还在Word文档已经打开的情况下设置了它,但是同样,它可以很容易地改变为你想从Excel中访问Word文档的任何方式。

Sub GetWordTable()
Dim wApp As Word.Application, doc As Word.Document
Set wApp = GetObject(, "Word.Application")
Set doc = wApp.ActiveDocument
doc.Tables(1).Range.Copy

Range("A1").PasteSpecial xlPasteValues

End Sub

最新更新