looping a find and delete row macro

2019-07-12 18:57发布

问题:

Please forgive the hand-holding that I'm sure I'm going to need on this question. I have very little experience with visual basic.

Here's what I'm trying to do: I have a large table in Word 2011 (Mac), and I need to find a certain string within the table and delete the row that contains it. Okay, no problem to do that by recording a macro. However, I'd like to have the macro find all instances and delete the rows all at once rather than having to run the macro over and over (besides which, after all the instances have been found, the dumb macro will delete the row where the cursor currently is even if the string isn't in that row!). I'm assuming I need some kind of while... loop, but I don't know how to do a Boolean test on Selection.Find - if that's even what I need to do!

Thanks in advance.

EDIT Code copy-pasted from comment and formatted:

Sub Macro2() ' ' Macro2 Macro ' '
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "pull from"
        .Replacement.Text = "Pain"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    Selection.Rows.Delete
End Sub

回答1:

So, I found an answer on another forum and thought I'd post it here:

With ThisDocument.Tables(1)
For r = .Rows.Count To 1 Step -1
        fnd = False
        For Each c In .Rows(r).Cells
            If InStr(c.Range.Text, "x") > 0 Then fnd = True
        Next
        If fnd Then .Rows(r).Delete
    Next
End With

where "x" is the text to be searched for.

Worked for me, although did take some time to loop through a 250 or so row table, so at first I thought that Word had frozen up. Also, the text string I entered ("x") had trouble at first finding an all-caps text string, so I had to put the search string in caps, too.

Additionally, I've found that this macro doesn't work unless it's copied into the word document where it needs to run. Changing ThisDocument to ActiveDocument allows it to work if it's only in the Normal template

Anyway, hope it helps someone!