There is a strange behavior in the following code that I can't understand:
Even though we have the loop:
For each tbl in doc.Tables
...
...
Next tbl
The code is not iterating through the 6 tables in doc
, but rather is "stuck" at the second table and adds all the data to that table, ignoring all the subsequent tables. I verified in the Interactive Window that all 6 tables are there. When I step through the code using F8, the code advances to Next tbl
and loops back to the beginning of the block, but even so tbl still points to table 2, and the data continues to get added to table 2, even though it "should" be at table 3 by this point.
Public const kSchedRow = 12
Dim wd as New Word.Application
Dim doc as Word.Document
Set doc = wd.documents.open(myFile)
Dim iTbl as integer 'Table #
iTbl = 1
For Each tbl In doc.Tables
'skip first table in "Header" and last two tables in "footer"
If Not (iTbl = 1 Or iTbl > doc.Tables.Count - 2) Then
With Sheets(kVS) 'Excel sheet where the data resides to fill into Word Tables
'Iterate through Excel table
For Each rw In .Range(Cells(kSchedRow + 2, 1), Cells(kSchedRow + 2, 1).End(xlDown))
'If the Excel data is intended for the current Word Table, then fill in data
If .Cells(rw.Row, 1) = iTbl - 1 Then
With tbl.Rows
With .Last.Range
.Next.InsertBefore vbCr 'Insert Paragraph after end of table
.Next.FormattedText = .FormattedText 'Make the Paragraph a row in table
End With
With .Last
'Add the Excel data to the Word Table
.Cells(1).Range.Text = CDate(Sheets(kVS).Cells(rw.Row, 2)) & " - " & _
CDate(Sheets(kVS).Cells(rw.Row, 3)) 'Time
.Cells(2).Range.Text = Sheets(kVS).Cells(rw.Row, 4) 'Company
.Cells(3).Range.Text = Sheets(kVS).Cells(rw.Row, 5) 'Address
.Cells(4).Range.Text = Sheets(kVS).Cells(rw.Row, 6) 'Telephone
.Cells(5).Range.Text = Sheets(kVS).Cells(rw.Row, 10)
End With
End With
End If
Next rw
End With
End If
iTbl = iTbl + 1
Next tbl
Any ideas what I'm doing wrong? I'm sure it's something very obvious, but I've been staring at the code for 4 hours and I just can't figure this out!