我试图通过VBA循环将Word文档的每个表复制到同一工作簿中的单独excel工作表中。 我在线找到了这个有用的解决方案,但它只复制一个工作表中的所有表。 Macro to export MS Word tables to Excel sheets
我该如何改善?
我尝试通过在处理每个表之后添加“ ActiveSheet.Next.Activate”来进行修改,以在处理第二个表之前激活下一个工作表,但是它仍然无法正常工作。任何帮助将不胜感激
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
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
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
'https://stackoverflow.com/questions/4465212/macro-to-export-ms-word-
tables-to-excel-sheets
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
Worksheets(1).Activate ' Activate the first worksheet
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
ActiveSheet.Next.Activate 'activate the next worsheet
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub