循环查找和删除行宏 [英] looping a find and delete row macro
问题描述
请原谅我确定在这个问题上需要的帮助.我对Visual Basic的经验很少.
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.
这是我要执行的操作:我在Word 2011(Mac)中有一个大表,并且我需要在表中找到一个特定的字符串并删除包含它的行.好的,通过录制宏可以做到这一点.但是,我想让宏查找所有实例并一次删除所有行,而不必一遍又一遍地运行宏(此外,在找到所有实例之后,哑宏将删除行所在的行)即使该字符串不在该行中,光标当前也位于该行!).我假设我需要某种while循环,但是我不知道如何对Selection.Find进行布尔测试-如果这甚至是我需要做的!
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!
先谢谢了.
编辑从注释复制粘贴并设置格式的代码:
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
推荐答案
因此,我在另一个论坛上找到了答案,并认为应该将其发布在这里:
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
其中"x"是要搜索的文本.
where "x" is the text to be searched for.
为我工作,尽管确实花了一些时间来遍历250个左右的行表,所以起初我认为Word已冻结.另外,我输入的文本字符串("x")最初在查找全大写字母的文本字符串时遇到了麻烦,因此我也不得不将搜索字符串也设置为大写字母.
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.
此外,我发现,除非将该宏复制到需要运行的Word文档中,否则该宏将不起作用.将此ThisDocument更改为ActiveDocument使其仅在普通模板中可以工作
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!
这篇关于循环查找和删除行宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!