Vba macro to copy row from table if value in table meets condition

后端 未结 4 1276
谎友^
谎友^ 2020-11-30 08:37

i\'m trying to make a macro which:

  1. goes through a table
  2. looks if value in column B of that table has a certain value
  3. if it has, copy that row
4条回答
  •  盖世英雄少女心
    2020-11-30 08:49

    Try it like this:

    Sub testIt()
    Dim r As Long, endRow as Long, pasteRowIndex As Long
    
    endRow = 10 ' of course it's best to retrieve the last used row number via a function
    pasteRowIndex = 1
    
    For r = 1 To endRow 'Loop through sheet1 and search for your criteria
    
        If Cells(r, Columns("B").Column).Value = "YourCriteria" Then 'Found
    
                'Copy the current row
                Rows(r).Select 
                Selection.Copy
    
                'Switch to the sheet where you want to paste it & paste
                Sheets("Sheet2").Select
                Rows(pasteRowIndex).Select
                ActiveSheet.Paste
    
                'Next time you find a match, it will be pasted in a new row
                pasteRowIndex = pasteRowIndex + 1
    
    
               'Switch back to your table & continue to search for your criteria
                Sheets("Sheet1").Select  
        End If
    Next r
    End Sub
    

提交回复
热议问题