简体   繁体   中英

VBA insert a formula to add value of cell to another

Im trying and failing to create a VBA formula for a command button which will take the value of cell S2 and add it with the value of the last cell of column G (this column is constantly being added to therefor making the row different each time). I want to place the result in the last cell of column I (again it is always being added to).

Help would be gratefully received, many thanks

This code would do that, you just need to have your command button run this sub:

Sub pasteLast()

Dim lrowG, lrowi As Integer

lrowG = Cells(Rows.Count, 7).End(xlUp).Row
lrowi = Cells(Rows.Count, 9).End(xlUp).Row

Cells(lrowi, 9).offset(1,0) = Range("s2") + Cells(lrowG, 7)

End Sub

just be careful because every time you click the button, it will add a value to column I whether it's unique or not. This would be better handled with a

Sub Worksheet_Change

event, where anytime S2 was changed it would add its value to column I.

Sounds like you need to find the last cell reference in column G, then go to 1 row past the last cell reference in column I, and as the cell reference in column G to S2.

This should work:

Sub addToI()

Dim gTarget As String

Range("G1").Select
Selection.End(xlDown).Select
gTarget = Selection.Address(ReferenceStyle:=xlR1C1)

Range("I1").Select
Selection.End(xlDown).Select
Selection.Offset(1, 0).Select

ActiveCell.FormulaR1C1 = "=" & gTarget & "+R2C19"

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM