mardi 31 mai 2016

If (search term) found, do (action). If not, end if

If you guys could help me out, that would be great because it would really help me.

Here's what I'm trying to do:

  1. Search for a cell with a specific term
  2. If found, copy the entire row that the cell is in and paste it into a row above it.
  3. If not found, do nothing and continue with the code

Here's my code:

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

My code only works if the value is found. If it's not found it runs into the error below: enter image description here

Aucun commentaire:

Enregistrer un commentaire