views:

57

answers:

1

I want to write a program in Visual Basic where I look at Column L of a worksheet and search for cells in Column L that contain "123." I then want to select the rows that contain "123" in Column L, copy them, and paste them into a new worksheet. How would I do this? I created a macro, but I'm not sure how to change it so that I can find multiple items and get all of the rows for those multiple items. Here's part of what the macro gave me:

Columns("L:L").Select
Selection.Find(What:="123", After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Activate
Rows("1058:1058").Select
Selection.Copy
Sheets("123").Select
Rows("4:4").Select
range("C4").Activate
Selection.Insert Shift:=xlDown
Rows("5:5").Select
range("C5").Activate
+3  A: 

Finds all 123s in the L column and copies the corresponding rows to Sheet2.
Tweak as needed.

Sub CopyRows()
  Dim FoundRange As Range
  Dim c As Range

  For Each c In Application.Intersect(Columns("L"), UsedRange)
    If c.Value like "*123*" Then
      If FoundRange Is Nothing Then
        Set FoundRange = c
      Else
        Set FoundRange = Application.Union(FoundRange, c)
      End If
    End If
  Next

  If Not FoundRange Is Nothing Then
    FoundRange.EntireRow.Copy Worksheets("Sheet2").Range("A4")
  End If

End Sub
GSerg
You may want If c.Value Like "*123*" to coincide with the xlPart of the Find the OP is using.
Dick Kusleika
@Dick I'm using at least 15 characters to agree with you.
GSerg