I have tried to write code to do the following:
1) I need VBA to first clear "Variance" in Col V if it exists as well as value in same row in Col W
2) I then need to insert "Variance" after last item in Col V on sheet "Data" and insert formula in Col W in the same rows as this text. The formula must = one row above Col W -2 rows above Col W
If "Variance" is in say V4, then formula must be =W3-W2 for example
Where "Variance" is in Col V, then code is inserting "Variance" 2 rows below last item when run a second time
See my code below
Sub ClearAndInsertVarianceAndFormula()
Dim lastDataRow As Long
Dim varianceRow As Long
' Set the sheet and column
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Data")
' Find the last row in Column V with data
lastDataRow = ws.Cells(ws.Rows.Count, "V").End(xlUp).Row
' Check if "Variance" already exists
Dim varianceCell As Range
Set varianceCell = ws.Columns("V").Find(What:="Variance", LookIn:=xlValues, LookAt:=xlWhole)
If Not varianceCell Is Nothing Then
' Get the row where "Variance" exists
varianceRow = varianceCell.Row
' Clear "Variance" and value in Column W in the same row
ws.Cells(varianceRow, "V").ClearContents
ws.Cells(varianceRow, "W").ClearContents
End If
' Insert "Variance" one row below the last row with data in Column V
ws.Cells(lastDataRow + 1, "V").Value = "Variance"
' Set the row where "Variance" is inserted
varianceRow = lastDataRow + 1
' Insert formula in Column W for the same row
ws.Cells(varianceRow, "W").Formula = "=" & ws.Cells(varianceRow - 1, "W").Address & "-" & ws.Cells(varianceRow - 2, "W").Address
End Sub
Bookmarks