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

前端 未结 2 735
南旧
南旧 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:43

    Without major changes to your existing sub. Replace:

    If Range("E" & CStr(LSearchRow)).Value = "Mail Box" Then
    

    with:

    v = Range("E" & CStr(LSearchRow)).Value
    If InStr(1, v, "red") > 0 Or InStr(1, v, "blue") > 0 Then
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题