I need to create two new columns that are right adjacent to a specific column which I'll call "Charged Amount". The two new columns will have two unique headers created....one will be called "Discrepancy - Amount" while the other will be called "Discrepancy - Percentage". Once that's done I need to run some basic formulas on those two new columns based on the presence of the "Charged Amount" values and another column (we'll call this "Inventory Amount"). I can get this to work with the code below if the "Charged Amount" column (Column Q in this case) and the "Inventory Amount" column (Column P here) are static.
Private Sub CommandButton1_Click()
Dim ChargedAmount As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Set ChargedAmount = Range("A1:Z1").Find("Charged Amount")
If ChargedAmount Is Nothing Then
MsgBox "Charged Amount column was not found."
Exit Sub
Else
Columns(ChargedAmt.Column).Offset(, 1).Resize(, 2).Insert
Range("R1").Select
ActiveCell.FormulaR1C1 = "Discrepancy - Amount"
Range("S1").Select
ActiveCell.FormulaR1C1 = "Discrepancy - Percentage"
Range("R2").Formula = "=(Q2-P2)"
Range("R2").Select
Selection.NumberFormat = "$#,##0.00"
Range("S2").Formula = "=(Q2/P2-1)"
Range("S2").Select
Selection.NumberFormat = "0.00%"
Range("R2").AutoFill Destination:=Range("R2:R" & lastRow)
Range("S2").AutoFill Destination:=Range("S2:S" & lastRow)
End If
End Sub
But I need something that's a bit more dynamic if the columns were to shift - basically keying in off just the names. Any help with this?
Private Sub CommandButton1_Click()
Dim ChargedAmount As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Set ChargedAmount = Range("A1:Z1").Find("Charged Amount")
If ChargedAmount Is Nothing Then
MsgBox "Charged Amount column was not found."
Exit Sub
Else
Columns(ChargedAmt.Column).Offset(, 1).Resize(, 2).Insert
Range("R1").Select
ActiveCell.FormulaR1C1 = "Discrepancy - Amount"
Range("S1").Select
ActiveCell.FormulaR1C1 = "Discrepancy - Percentage"
Range("R2").Formula = "=(Q2-P2)"
Range("R2").Select
Selection.NumberFormat = "$#,##0.00"
Range("S2").Formula = "=(Q2/P2-1)"
Range("S2").Select
Selection.NumberFormat = "0.00%"
Range("R2").AutoFill Destination:=Range("R2:R" & lastRow)
Range("S2").AutoFill Destination:=Range("S2:S" & lastRow)
End If
End Sub
But I need something that's a bit more dynamic if the columns were to shift - basically keying in off just the names. Any help with this?