Excel: How to copy a row if it contains certain text to another worksheet (VBA)

℡╲_俬逩灬. 提交于 2019-11-30 20:59:33

问题


I'm looking to use a marco that would be able to search a column in said sheet and if certain text is found - in my case the word "FAIL" - copy that entire rows data/formatting and paste it into another sheet - sheet 4 in my case - along with any other rows that contained that specific text.

i have been using this code but it only copy pastes one row then stops rather than going through and copying any rows with "FAIL"

Sub Test()
For Each Cell In Sheets(1).Range("H:H")
  If Cell.Value = "FAIL" Then
    matchRow = Cell.Row
    Rows(matchRow & ":" & matchRow).Select
    Rows(matchRow & ":" & matchRow).Select
    Selection.Copy

    Sheets(4).Select
    ActiveSheet.Rows(matchRow).Select
    ActiveSheet.Paste
    Sheets(4).Select
   End If
Next 
End Sub

First post and brand new to VBA so apologies if too vague.


回答1:


Try the code below (explanation inside the code as comments):

Option Explicit

Sub Test()

Dim Cell As Range

With Sheets(1)
    ' loop column H untill last cell with value (not entire column)
    For Each Cell In .Range("H1:H" & .Cells(.Rows.Count, "H").End(xlUp).Row)
        If Cell.Value = "FAIL" Then
             ' Copy>>Paste in 1-line (no need to use Select)
            .Rows(Cell.Row).Copy Destination:=Sheets(4).Rows(Cell.Row)
        End If
    Next Cell
End With

End Sub



回答2:


Try like this:

Option Explicit

Sub TestMe()

    Dim Cell As Range
    Dim matchRow As Long

    With Worksheets(1)    
        For Each Cell In .Range("H:H")
            If Cell.Value = "FAIL" Then
                matchRow = .Cell.Row
                .Rows(matchRow & ":" & matchRow).Select
                .Rows(matchRow & ":" & matchRow).Select
                Selection.Copy        
                Worksheets(4).Select
                Worksheets(4).Rows(matchRow).Select
                Worksheets(4).Paste
                .Select
            End If
        Next        
    End With
End Sub

The problem in your code is that you do not reference the worksheets all the time correctly. Thus it does not work correctly.

As a 2. step, you can try to avoid all the selections in your code, it is a best practice to avoid using either Select or Activate in Excel VBA.



来源:https://stackoverflow.com/questions/45209392/excel-how-to-copy-a-row-if-it-contains-certain-text-to-another-worksheet-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!