Search code examples
excelvbaconditional-statementscopymultiple-conditions

How do I copy certain cells from one sheet to another conditional on the cell value in both sheets?


I have a range of non-contiguous cells that I want to copy across from one sheet (wseDNA1) to a second sheet (wsElog1). I only want to copy if the value in wseDNA1 is not "NR", and if the cell in wsElog1 does not already contain a value. I wanted to do a loop, but am not sure how to do this without it looking at every cell, and not just the cells I want to copy. Below is an example of the copy range without the conditional rules. I will have more than a hundred of these to map across every day.

wsElog1.Range("BP" & RowNum) = wseDNA1.Range("AE12") 
wsElog1.Range("BQ" & RowNum) = wseDNA1.Range("AG12") 
wsElog1.Range("BN" & RowNum) = wseDNA1.Range("AO12") 
wsElog1.Range("BR" & RowNum) = wseDNA1.Range("AQ12") 
wsElog1.Range("BS" & RowNum) = wseDNA1.Range("AS12") ```

Solution

  • Loop and Conditionally Copy Values

    • This is how far I got. If you can share the information that I asked for in your comments, it will get better.
    Sub Test()
        
        ' Make sure these two have the same number of elements
        ' and that they are correctly associated.
        Dim dCols() As Variant: dCols = VBA.Array("AE", "AG", "AO", "AQ", "AS")
        Dim eCols() As Variant: eCols = VBA.Array("BP", "BQ", "BN", "BR", "BS")
        
        Dim nUpper As Long: nUpper = UBound(dCols)
        
        Dim dVal As Variant, RowNum As Long, n As Long, eCol As String
        
        For n = 0 To UBound(dCols)
            dVal = wsDNA1.Cells(12, dCols(n)).Value
            If StrComp(CStr(dVal), "NR", vbTextCompare) <> 0 Then
                eCol = eCols(n)
                For RowNum = 2 To 3 ' adjust!
                    If Len(CStr(wsElog1.Cells(RowNum, eCol).Value)) = 0 Then
                        wsElog1.Cells(RowNum, eCol).Value = dVal
                    End If
                Next RowNum
            End If
        Next n
    
    End Sub