Search code examples
vbaexcelexcel-2007

Place a formula in every cell in column N for which there is a value two columns to the left


How do I place a formula in every cell in column N for which there is a value two columns to the left (in column L)?

 Sub KeepOnlyAtSymbolRows()
        Dim ws As Worksheet
        Dim rng1, rng2 As Range
        Dim lastRow, LASTROW2 As Long

    LASTROW2 = ws.Range("L" & ws.Rows.Count).End(xlUp).Row
         Set rng2 = ws.Range("L2" & LASTROW2)
         'Debug.Print rng2
         For Each cell In rng2
            cell.offset()
            cell.Formula = "foo bar etc"
            Next cell
    End Sub

Solution

  • Maybe try:

    Sub KeepOnlyAtSymbolRows()
    Dim rng2 As Range
    Dim LASTROW2 As Long
        LASTROW2 = Range("L" & Rows.Count).End(xlUp).Row
        Set rng2 = Range("N1:N" & LASTROW2)
        For Each cell In rng2
            If cell.Offset(0, -2) <> "" Then
            cell.Formula = "foo bar etc"
            End If
         Next cell
    End Sub  
    

    You seem not to be applying rng1 nor lastRow and not setting the ws value anyway. And if you were and wanted to dimension as Range/Long then in VBA you need to Pay Attention To Variables Declared With One Dim Statement.

    You are trying to set rng2 with syntax that would give something like L29 if 9 is your last occupied row in ColumnL.

    Since I think it is ColumnN you want to populate I think rng2 should be based on that, even if using ColumnL to determine the last populated row.

    It seems you want a conditional (<> "" is interpreted as "not blank") and .offset needs parameters ((0,-2) is interpreted as "same row, two columns to the left").