问题
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