Delete rows from a table

S

SoNew2This

What I'd like to do is delete rows from a table if a specific cell does not
equal a certain value. I'm don't even know where to start, so several
helpful hints would be appriciated.
 
G

Greg Maxey

Sub ScratchMaco()
Dim oTbl As Word.Table
Dim oRow As Word.Row
Dim oCell As Word.Cell
Dim oRng As Word.Range
Set oTbl = Selection.Tables(1) 'The table the IP is located in
For Each oRow In oTbl.Rows
Set oCell = oRow.Cells(2) 'The specific cell (e.g., second cell in row)
Set oRng = oCell.Range
oRng.End = oRng.End - 1 'Strip end of cell marker
If oRng.Text <> "Test" Then 'The test text
oRow.Delete
End If
Next oRow
End Sub
 
F

Fumei2 via OfficeKB.com

How specific a cell????

Sub IfNotX()
Dim oTbl As Table
Dim oCell As Cell
Set oTbl = ActiveDocument.Tables(1)
' or Greg's Set oTbl = Selection.Tables(1) 'The table the IP is located in
For Each oCell In oTbl.Range.Cells
If CellText(oCell) = 50 Then
oTbl.Rows(oCell.RowIndex).Delete
End If
Next
End Sub

will delete ANY row, if ANY cell in that row = 50.

Note the use of the CellText function (passing in the cell as an object).
Also note that it uses Range.Cells - plural; rather than Table.Cell -
(singular) (row, column)

Gerry
 
S

SoNew2This

This worked as I was hoping, but for some reason I need to place the cursor
within the first cell of the table. Shouldn't the 'Set oTbl =
Selection.Tables(1)' do this? If not how can I get the cursor into the first
cell so this code will work?
 
J

Jay Freedman

The expression 'Selection.Tables(1)' means 'the first (usually the
only) table within the selected text'. That's different from
ActiveDocument.Tables(1), which means 'the first table in the
document'. Since the document might have more than one table, Greg's
macro depends on you putting the cursor in the table you want the
macro to work on.

If you know there is only one table in the document, or if you always
want to work on only the first table, then you can change the line in
the macro to say Set oTbl = ActiveDocument.Tables(1). Otherwise,
you'll have to figure out some other way for the macro to 'know' which
table is the right one.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top