开发者

In Visual Basic for Excel 2007, how do I select rows that contain a certain pattern?

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开发者_JS百科 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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜