简体   繁体   中英

VBA: Copy cell in worksheet1 to worksheet2 based on value of cell

Using VBA, how do I:

Copy cell B1 in Worksheet1 to a new Worksheet2 only if cell A1 (in Worksheet1) value = "YES".

This then repeats for each row in range A1:A1000 (ie B2 copies based on A2 value = "YES" and so on) - if cell is blank, check next row.

Sub Output()
Dim c As Range
    Dim j As Integer
    Dim Source As Worksheet
    Dim Target As Worksheet

    Set Source = ActiveWorkbook.Worksheets("worksheet1")
    Set Target = ActiveWorkbook.Worksheets("worksheet2")

    j = 1     ' Start copying to row 1 in target sheet
    For Each c In Source.Range("R2:R1000")   ' Do 1000 rows
        If c = "YES" Then
           Source.Rows(c.Row).Copy Target.Rows(j) /*getting stuck here on trying to copy a cell from column S in worksheet1 to worksheet2
           j = j + 1
        End If
    Next c
End Sub

You just need a quick modification to change from copying the row to the individual cells and location. I used that you are copying from column AG in row c.

Sub Output()
Dim c As Range
Dim j As Integer
Dim Source As Worksheet
Dim Target As Worksheet

Set Source = ActiveWorkbook.Worksheets("workshee1")
Set Target = ActiveWorkbook.Worksheets("workshee2")

j = 1     ' Start copying to row 1 in target sheet
    For Each c In Source.Range("R2:R1000")   ' Do 1000 rows
        If c = "YES" Then
            Target.Cells(j, "A").Value = Source.Cells(c.Row, "AG").Value
            j = j + 1
        End If
    Next c
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM