我正在尝试创建一种自动化方法来清理文档。我将一个txt文件打开到excel中,然后将所有内容转储到A列中。我编写了一个脚本,将信息格式化为列。然后,我需要在doc中搜索一串文本,然后我删除该行加上10行。我已经设法完成了这个,但当它到达没有更多行与指定文本的点时,我得到一个运行时91错误。
只是一点点背景,我对使用VBA很新。所以这可能是一个非常基本的修复。
我也在想也许我可以运行一个查找此文本字符串的宏并首先删除行,这样它只能在A列而不是多列中搜索。
以下是我正在使用的代码。几乎在网上发现它,只是改变它以满足我的需求
希望有人可以告诉我自己做错了什么或建议另外一种方法来完成这项工作。
谢谢
Sub FindAndDelete()
Dim found As Range
Do Until found = False
Set found = ActiveSheet.Columns("A:R").Find(what:="Based on Positions as of Month-End, No Pa", LookIn:=xlValues, lookat:=xlWhole)
found.EntireRow.Select
found.EntireRow.Delete
ActiveCell.Offset(0, 0).EntireRow.Delete
ActiveCell.Offset(0, 0).EntireRow.Delete
ActiveCell.Offset(0, 0).EntireRow.Delete
ActiveCell.Offset(0, 0).EntireRow.Delete
ActiveCell.Offset(0, 0).EntireRow.Delete
ActiveCell.Offset(0, 0).EntireRow.Delete
ActiveCell.Offset(0, 0).EntireRow.Delete
ActiveCell.Offset(0, 0).EntireRow.Delete
ActiveCell.Offset(0, 0).EntireRow.Delete
ActiveCell.Offset(0, 0).EntireRow.Delete
Loop
End Sub
答案 0 :(得分:1)
请参阅注释以获取解释
Sub FindAndDelete()
Dim rngFound As Range
Do '/ Loop at least once before validating condition
'/ Use Worksheet name/codename instead of ActiveSheet.
Set rngFound = Sheet2.Columns("A:R").Find( _
what:="Based on Positions as of Month-End, No Pa", _
LookIn:=xlValues, lookat:=xlWhole)
'/ Ensure that we found something. If Yes then delete
'/ If you don't check this, error 91 pops up in case nothing is
'/ found.
If Not rngFound Is Nothing Then
rngFound.EntireRow.Delete
End If
Loop While Not rngFound Is Nothing
End Sub