Excel: set default formula for each cell in column

autocompletemicrosoft excelworksheet-function

I have a column with the following formula in every cell that calculates the difference in kilometers between the two cells to the left of each cell:

=IF(AND(INDIRECT(ADDRESS(ROW(),COLUMN()-2))<>"", INDIRECT(ADDRESS(ROW(), COLUMN()-1))<>""), INDIRECT(ADDRESS(ROW(),COLUMN()-1))-INDIRECT(ADDRESS(ROW(),COLUMN()-2)), "")

empty cell with no formula when I insert a new row

My problem is that every time I insert a new row in between existing data, all the cells are empty in that row and I need to manually put this code into the empty cell.

Is it possible for me to set every cell in a column (excluding the header) to a specific formula even when I insert a new row?

I have tried to set the column as a table, and it was successful in autocompleting the cells whenever I inserted a new row, however, I have other columns that I also want to autocomplete and Excel doesn't let me insert a new row if I make more than one column a table.

Best Answer

Here is a small demo that you can adapt to your actual schema. In the demo:

  1. the column of interest is column B
  2. if more than one row is inserted, nothing will happen
  3. if a row below the data area is inserted, nothing happens
  4. if a row is deleted, nothing happens
  5. if a row in the middle of the data is inserted, the cell in column B will be filled with either the formula above or the formula below
  6. if there is no formula above or below the new cell, nothing happens

Insert the following sub in the worksheet code area:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim r As Range, r1 As Range, r2 As Range

    Set r = Target
    If r.Rows.Count > 1 Then Exit Sub
    If r.Columns.Count <> Cells.Columns.Count Then Exit Sub
    If r.Row = 1 Then Exit Sub

    Set r1 = Intersect(r, Columns(2))
    If r1.Value <> "" Then Exit Sub

    If r1.Offset(-1, 0).HasFormula Then
        Application.EnableEvents = False
            r1.Offset(-1, 0).Copy r1
        Application.EnableEvents = True
        Exit Sub
    End If

    If r1.Offset(1, 0).HasFormula Then
        Application.EnableEvents = False
            r1.Offset(1, 0).Copy r1
        Application.EnableEvents = True
        Exit Sub
    End If

End Sub
Related Question