I changed it up a little in that you browse for a file location and select the files you want to process. It's been my experience to only select 50-100 files to work on at a time. Keeps Word from bogging things down.
Also, after I created a few extra files for testing, the first name and surname get separated on the Excel sheet due to the row order verses column order.
The way it's written now, it can handle tables that have different column counts.
Hope this helps!
Option Explicit
Sub ImportWordTable()
Dim WS As Worksheet
Dim A As Long, B As Long
Dim I As Long, J As Long
Dim xlCol As Long
Dim NextRow As Long
Dim FN As Variant
Dim CellData As String
Dim WordPath As String
Dim wrdApp As Object
Dim wrdDoc As Object
On Error Resume Next
' Get existing instance of Word if it exists.
Set wrdApp = GetObject(, "Word.Application")
If Err <> 0 Then
' If GetObject fails, then use CreateObject instead.
Set wrdApp = CreateObject("word.application")
End If
On Error GoTo 0
'Path to word files.
'Use this if you want Excel to always browse for files at a certain location.
'ChDir "C:\Users\Owner\Documents\VBA\ExcelForum\"
FN = Application.GetOpenFilename("Word Files (*.doc), *.doc", _
, "Navigate to folder containing Word Files", , True)
Set WS = Worksheets(1)
With WS
'Determine last row with data and add one.
NextRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
For J = 1 To UBound(FN)
'Test for wrdApp existance.
If Not wrdApp Is Nothing Then
'Open the work doc.
Set wrdDoc = wrdApp.Documents.Open(FN(J))
For I = 1 To wrdDoc.tables.Count
'Iterate the Word tables, row by row
For A = 2 To wrdDoc.tables(I).Rows.Count Step 2
'Column Counter for Excel sheet.
For B = 1 To wrdDoc.tables(I).Columns.Count
'Assign value in Word Table to a variable.
CellData = wrdDoc.tables(I).Cell(A, B).Range.Text
'Strip off Word table cell markers and assign to Excel sheet.
xlCol = xlCol + 1 'Excel Column Counter
WS.Cells(NextRow, xlCol) = Left(CellData, Len(CellData) - 2)
Next
Next
Next 'Next Table
'Add filename to sheet.
WS.Cells(NextRow, xlCol + 1) = FN
'Close Word document, do not save changes.
wrdDoc.Close False
'Increment nextrow and clear Excel column counter.
NextRow = NextRow + 1: xlCol = 0
End If
Next
End With
Set wrdDoc = Nothing
Set wrdApp = Nothing
End Sub
Bookmarks