PDA

View Full Version : Loop Through Tables After Page Break



Lingster
05-06-2016, 08:25 AM
Hi, very newbie here.

I'm attempting to create a macro to loop through a table, reference the file name of a picture in one row, insert that picture in the row below, and create a page break after that row. The table is structured with 1 column and 1 row, with file names in alternating rows.

My code works to accomplish this task, but with the page break a new table is created. I therefore am attempting to loop through all subsequent tables. This is the code:


Sub InstertImage()Dim imagepath As String
Dim strFile As Range
Dim strFolder As String
Dim celTable As Cell
Dim i As Integer
Dim j As Integer


i = 1


For j = 1 To j = 5
For Each celTable In ActiveDocument.Tables(j).Rows(i).Cells
strFolder = "M:\MyFilePath\"
Set strFile = ActiveDocument.Range(Start:=celTable.Range.Start, End:=celTable.Range.End - 1)
imagepath = strFolder & strFile.Text
ActiveDocument.InlineShapes.AddPicture _
FileName:=imagepath, _
LinktoFile:=False, _
SaveWithDocument:=True, _
Range:=ActiveDocument.Tables(j).Rows(i + 1).Cells(1).Range
Next celTable
ActiveDocument.Tables(j).Rows(i + 2).Cells(1).Range.InsertBreak Type:=wdPageBreak
Next j


End Sub


When I run this code, nothing happens, no errors, no changes, nothing.

If I remove the For j=1 to j=5 and Next j lines and simply define j=1 and then the same code with j=2, the code works fine. Is there something different about looping through tables instead of rows/columns?

Lingster
05-06-2016, 08:59 AM
Ah yes...simply should be For j=1 to 5 to begin the loop, not j=1 to j=5

The mistakes beginners make.

gmaxey
05-06-2016, 09:35 AM
Does your table looks something like this:



To each his own, but you should try to be consistent with variable naming:


Sub InstertImage()
Dim strFolder As String
Dim oTbl As Word.Table
Dim strImagePath As String
Dim oRng As Range
Dim oCell As Cell
Dim lngRow As Integer
Dim lngIndex As Long

strFolder = "C:\" '"M:\MyFilePath\"
lngRow = 1
For lngIndex = 1 To 5
Set oTbl = ActiveDocument.Tables(lngIndex)
For Each oCell In ActiveDocument.Tables(lngIndex).Rows(lngRow).Cells
Set oRng = oCell.Range
oRng.End = oRng.End - 1
strImagePath = strFolder & oRng.Text
ActiveDocument.InlineShapes.AddPicture FileName:=strImagePath, _
LinktoFile:=False, SaveWithDocument:=True, _
Range:=oTbl.Rows(lngRow + 1).Cells(1).Range
Next oCell
ActiveDocument.Tables(lngIndex).Rows(lngRow + 2).Cells(1).Range.InsertBreak Type:=wdPageBreak
Next lngIndex
lbl_Exit:
Exit Sub
End Sub