How can I modify the following to loop over the first column of a table in word rather than applying it to all cells of a table?
Additionally, how can I have this iterate over every table within the document?
Sub AddToEveryCell()
Dim tbl As Table
Dim rw As Row
Dim cl As Cell
If Selection.Information(wdWithInTable) Then
Set tbl = ActiveDocument.Tables(1)
For Each rw In tbl.Rows
For Each cl In rw.Cells
cl.Range.Text = _
Left(cl.Range.Text, Len(cl.Range.Text) - 2) _
& "|" ' <= the character you want to add
Next cl
Next rw
Else
MsgBox "Put the cursor in the table and rerun this macro."
End If
End Sub
Attempt I have explored is:
Dim tbl As Table
Dim rw As Row
Dim cl As Cell
If Selection.Information(wdWithInTable) Then
Set tbl = ActiveDocument.Tables(1)
For Each rw In tbl.Rows
cl = rw.Cells(1) ' only loop through the first column
cl.Range.Text = _
Left(cl.Range.Text, Len(cl.Range.Text) - 2) _
& "|" ' <= the character you want to add
Next rw
Else
MsgBox "Put the cursor in the table and rerun this macro."
End If
However, I am getting an invalid use of property error.
CodePudding user response:
I tried the second of your attempts and initially got the same error as you. Then I added a "Set" before cl = rw.Cells(1), I had a vague memory of having this problem before... then it worked just fine. Objects and variables needs to be assigned using set, according to https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/set-statement
I pasted the macro that worked on my computer below.
Sub q2()
'
Dim tbl As Table
Dim rw As Row
Dim cl As Cell
If Selection.Information(wdWithInTable) Then
Set tbl = ActiveDocument.Tables(1)
For Each rw In tbl.Rows
Set cl = rw.Cells(1) ' only loop through the first column
Debug.Print "in for"
cl.Range.Text = _
Left(cl.Range.Text, Len(cl.Range.Text) - 2) _
& "|" ' <= the character you want to add
Next rw
Else
MsgBox "Put the cursor in the table and rerun this macro."
End If
'
'
End Sub
CodePudding user response:
Try the following if statement :
If Selection.Information(wdWithInTable) Then
For Each tbl In ActiveDocument.Tables ' loop through all tables in the document
For Each rw In tbl.Rows
cl = rw.Cells(1) ' only loop through the first column
cl.Range.Text = _
Left(cl.Range.Text, Len(cl.Range.Text) - 2) _
& "|" ' <= the character you want to add
Next rw
Next tbl
Else
MsgBox "Put the cursor in the table and rerun this macro."
End If
Hope this helps