Delete rows whenever cells in the first column of tables start with a specific string (using VBA)

Dear Experts:

My current document features several tables.

There are cells in the first column of the tables that start with the string 'X_'

I would like to run a macro that deletes the whole row whenever table cells in the first column start with that string 'X_'

The macro is to tell in a Msgbox how many rows have been deleted, if any.

Help is much appreciated. Thank you very much in advance.

Regards, Andreas
Andreas HermleTeam leaderAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.


pls try
Sub macro()

For Each tbl In ActiveDocument.Tables
    For Each rw In tbl.Rows
        If rw.Cells(1) Like "X_*" Then
            rwCnt = rwCnt + 1
        End If
If rwCnt > 0 Then MsgBox rwCnt & " row(s) were deleted."
End Sub

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Subodh Tiwari (Neeraj)Excel & VBA ExpertCommented:
You may try something like this...
Sub DeleteTableRows()
Dim doc As Document
Dim tbl As Table
Dim cell As cell
Dim cnt As Long

Set doc = ActiveDocument
For Each tbl In doc.Tables
    For Each cell In tbl.Columns(1).Cells
        If Left(cell.Range.Text, 2) = "X_" Then
            cnt = cnt + 1
        End If
    Next cell
Next tbl
MsgBox "Total " & cnt & " rows have been deleted.", vbInformation
End Sub

Open in new window

Andreas HermleTeam leaderAuthor Commented:
Dear both,

both solutions work just fine, thank you very much for it.

I can learn from both :-)

Since Rgonzo (Rafael) was quicker and his code is more concise, I suggest awarding him the most points.

It is always hard for me to award points ...

Thank you very much for your great and professional help.

Regards, Andreas
Subodh Tiwari (Neeraj)Excel & VBA ExpertCommented:
You're welcome Andreas! Glad we could help.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Word

From novice to tech pro — start learning today.