Search code examples
excelvbacopyconditional-statementscriteria

How to copy a column if the criteria is met within the same worksheet


I am trying to copy column B into column E based off of a criteria in C. However, I can't seem to figure out how to copy the data into the matching row .

For example , I would like it be executed like this { matching with the corresponding text in column B to E if column (C=x)}

Column > A | B | C | D | E


         A   X       A
         B   Y
         C   X       C

Here's what I have

Dim x As Integer
Dim textSG As String
Dim erow As Long

x = 3 
erow = 0

Do while Worksheet.Cell(x, 3) <> ""    
    If InStr ((Worksheet.Cells(x, 3)),"X" > 0 Then    
        textSG = Worksheet.Cells(x, 2)    
        erow = erow + 3    
        Worksheet.Cells(erow, 5) = textSG
    End if 
    x = x + 1 
Loop

Solution

  • Please try this code. I think it does what you intend.

    Dim R       As Long
    
    For R = 3 To Cells(Rows.Count, 3).End(xlUp).Row
        ' case insensitive comparison
        If StrComp(Trim(Cells(R, 3).Value), "x", vbTextCompare) = 0 Then
            Cells(R, 5).Value = Cells(R, 2).Value
        End If
    Next R