简体   繁体   English

VBA插入公式以将单元格的值添加到另一个

[英]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).我尝试并未能为命令按钮创建一个 VBA 公式,该公式将获取单元格 S2 的值并将其与 G 列的最后一个单元格的值相加(此列不断添加到其中,从而使行每次都不同) . I want to place the result in the last cell of column I (again it is always being added to).我想将结果放在 I 列的最后一个单元格中(同样它总是被添加到)。

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.请小心,因为每次单击按钮时,它都会向 I 列添加一个值,无论它是否唯一。 This would be better handled with a这会更好地处理

Sub Worksheet_Change

event, where anytime S2 was changed it would add its value to column I.事件,只要 S2 发生更改,它就会将其值添加到 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.听起来您需要找到 G 列中的最后一个单元格引用,然后转到 I 列中最后一个单元格引用之后的 1 行,并将 G 列中的单元格引用作为到 S2 的单元格引用。

This should work:这应该有效:

Sub addToI()子 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结束子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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