Make vba excel function dynamic with the reference cells

旧街凉风 提交于 2020-07-20 03:44:33

问题


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


回答1:


With .Formula you need to add a formula like you would add it manually into the Excel cell like .Formula("=SumProduct(…)") so the formula is recalculated by Excel automatically. To get the address of a range and use it in your formula use the Range.Address method.


Instead of a loop just fill out the formula for the first cell 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) & ")"

and then auto fill that cell right into the others (up to p = 12)

ActiveSheet.Cells(LastRow + 2, 32).AutoFill Destination:=Range(Cells(LastRow + 2, 32), Cells(LastRow + 2, 43))

After that the sum product automatically recalculates if you change any values.



来源:https://stackoverflow.com/questions/44653338/make-vba-excel-function-dynamic-with-the-reference-cells

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!