I have written a code which creates a sumproduct of two range.... But I want the final answer to change when the reference ranges whose sumproduct is been calculated is changed
p = 1
For p = 1 To 12
ActiveSheet.Cells(LastRow + 2, 31 + p).Formula = WorksheetFunction.SumProduct(Range(Cells(3, 31 + p), Cells(LastRow, 31 + p)), Range(Cells(3, 6 + p), Cells(LastRow, 6 + p)))
Next p
for example in the above sheet the sumproduct result is shown in the lastrow+2 th row and from column 31 to 42, but when i change the reference cells the answer doesnt change how to make my end result dynamic with the input
答案 0 :(得分:0)
使用.Formula
,您需要添加一个公式,就像将其手动添加到Excel单元格中一样.Formula("=SumProduct(…)")
,以便Excel自动重新计算公式。要获取范围的地址并在公式中使用它,请使用Range.Address method。
只需填写第一个单元格p = 1
ActiveSheet.Cells(LastRow + 2, 32).Formula = "=SumProduct(" & Range(Cells(3, 32), Cells(LastRow, 32)).Address(False, False) & ", " & Range(Cells(3, 7), Cells(LastRow, 7)).Address(False, False) & ")"
然后自动将该单元格填充到其他单元格中(最多p = 12
)
ActiveSheet.Cells(LastRow + 2, 32).AutoFill Destination:=Range(Cells(LastRow + 2, 32), Cells(LastRow + 2, 43))
之后,如果您更改任何值,sum产品会自动重新计算。