Excel regular expression macro that will search one column for matches, paste the entire row of all matches in another worksheet

前端 未结 2 733
南旧
南旧 2021-02-11 02:25

I need to be able to use regular expressions in an excel macro that will search through a specific column, and then copy and paste all the rows that contain matches into a new s

2条回答
  •  天涯浪人
    2021-02-11 02:44

    Sub SearchForString()
    
        Dim RE As Object
        Dim LSearchRow As Long
        Dim LCopyToRow As Long
    
        On Error GoTo Err_Execute
    
        Set RE = CreateObject("vbscript.regexp")
        RE.Pattern = "(red|blue)"
        RE.Ignorecase = True
    
        LSearchRow = 4 'Start search in row 4
        LCopyToRow = 2 'Start copying data to row 2 in Sheet2 (row counter variable)
    
        While Len(Cells(LSearchRow, "A").Value) > 0
    
         If RE.Test(Cells(LSearchRow, "E").Value) Then
             ActiveSheet.Rows(LSearchRow).Copy Sheets("Sheet2").Rows(LCopyToRow)
             LCopyToRow = LCopyToRow + 1 'Move counter to next row
         End If
    
         LSearchRow = LSearchRow + 1
    
        Wend
    
        Range("A3").Select 'Position on cell A3
        MsgBox "All matching data has been copied."
    
        Exit Sub
    
    Err_Execute:
        MsgBox "An error occurred."
    
    End Sub
    

提交回复
热议问题