如果(search词)find,则执行(动作)。 如果不是,结束如果

如果你们能够帮助我,这将是非常棒的,因为这对我真的很有帮助。

这是我想要做的:

  1. search具有特定术语的单元格
  2. 如果find,则复制单元格所在的整行,并将其粘贴到其上方的一行中。
  3. 如果没有find,则不要执行任何操作并继续执行代码

这是我的代码:

Sub Test() ' ' Test Macro ' ' Keyboard Shortcut: Ctrl+b ' Range("A5").Select Cells.Find(What:="PL 1", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate If Not IsEmpty(ActiveCell.Value) Then ActiveCell.Rows("1:1").EntireRow.Select Selection.Copy Range("A5").Select ActiveSheet.Paste End If Range("A5").Select Cells.Find(What:="PL 2", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate If Not IsEmpty(ActiveCell.Value) Then ActiveCell.Rows("1:1").EntireRow.Select Selection.Copy Range("A6").Select ActiveSheet.Paste End If Range("A5").Select Cells.Find(What:="PL 3", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate If Not IsEmpty(ActiveCell.Value) Then ActiveCell.Rows("1:1").EntireRow.Select Selection.Copy Range("A7").Select ActiveSheet.Paste End If End Sub 

我的代码只有在find该值时才有效。 如果没有find它会遇到下面的错误: 在这里输入图像说明

Cells.Find是一个返回Range对象引用的函数; 当它没有find任何东西时,引用将是Nothing 。 而你不能打电话。

如果找不到匹配项,此方法返回Nothing。 Find方法不影响select或活动单元格。 ( MSDN )

 Cells.Find(What:="PL 2", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate 

你需要重写你的代码,并避免。select和。激活 ,避免使用ActiveCellActiveSheet (你正在做的不是通过适当的工作表引用限定Cells 格调用)隐式的工作。

你的格式很难阅读代码,原因如下:

  • 参数正在不同的行上指定
  • 线路延续正在任意位置
  • 嵌套的成员电话不排队

相比于:

 Cells.Find(What:="PL 2", After:=ActiveCell, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) _ .Activate 

这只是可读性。 问题是你基本上认为 .Find返回一个有效的对象引用。 不要假设,明确检查:

 Set result = Cells.Find(...) If Not result Is Nothing Then result.Activate 

但是,真的,你需要找出一种方法来避免。select和。激活。

你可以尝试这样的事情(未经testing):

 Sub HideAndSeek() Dim foundCell As Range For i = 1 To 3 Set foundCell = Cells.Find(What:="PL " & i, LookIn:=xlFormulas, LookAt:=xlPart) If Not foundCell Is Nothing Then Intersect(foundCell.EntireRow, ActiveSheet.UsedRange).Offset(-1, 0).Value = _ Intersect(foundCell.EntireRow, ActiveSheet.UsedRange).Value End If Set foundCell = Nothing Next End Sub 

原则是你编写你需要的代码,然后创build一个循环来为你重复代码。

这个答案的另一部分是检查单元格是否被find – 为此,我们检查范围是否被实际设置(这意味着它不是Nothing

 If Not foundRange Is Nothing