PDA

View Full Version : A loop & string operators



bigal.nz
11-24-2014, 09:41 AM
Morning VBA peoples,

I need to make one big string from each row in a table, then past that big string into each row in a Outlook template.

The logic would be something like:

For each row in ActiveDocument.Table(3) 'Starting at Row 3
BigString = String.Column1 & String.Column2 & String.Colum3 & String.Colum4
Insert BigString in OutlookTemplateObject.Table(1).Column3
Loop Next Row ActiveDocument.Table(3) Until End of Rows

This may seem simple but I haven't used VBA for a while and my skills are rusty.

I have my outlook template open OK.

Its really just the loop that was throwing me.

ActiveDocument.Table(3) is fixed at 4 colums with two header rows (hence start at row3).

The Outlook table is also fix at 3 columns, no header row. I dont need to insert rows as I go since the outlook table has been made to be more than long enough.

Thanks in advance,

-Al

bigal.nz
11-25-2014, 10:40 AM
I got something like:



Set oTable = ThisDocument.Range.Tables(3)
Set oRng = oTable.Range


For x = ThisDocument.Tables(3).Rows.Count - 2 To ThisDocument.Tables(3).Rows.Count
For y = 1 To 4
MsgBox (oTable.Cells(x, y))
Next y
Next x


But I don't understand that working with things like oRng properly. I assume the notation "o" is for Object? and Rng for range.

Im using thisdocument because once I can reference the values in the cells I want to make a big string I will then past into a outlook object, so I need to switch between the windows, and activedocument gives me the outlook object.

Al

macropod
11-25-2014, 06:44 PM
It's not especially important what the variables are called. What matters is that they're used correctly. Having a consistent and meaningful naming convention helps with code maintenance, but VBA couldn't care less about that.

To loop though all the cells, starting from the 1st cell on the 3rd row, you could use code like:

Sub Demo()
Dim RngTbl As Range, RngData As Range, i As Long
With ActiveDocument
Set RngTbl = .Range(.Tables(1).Cell(3, 1).Range.Start, .Tables(1).Range.End)
With RngTbl
For i = 1 To .Cells.Count
Set RngData = .Cells(i).Range
RngData.MoveEnd wdCharacter, -1
MsgBox RngData.Text
Next
End With
End With
End Sub
Note that I've used two range objects - one to define the overall range I'm interested in; the other to reference each cell's contents. The reason for 'RngData.MoveEnd wdCharacter, -1' is to eliminate the cell's end-of-cell marker from the output.

bigal.nz
11-27-2014, 07:48 PM
Thanks