问题
I'm writing a code that will add a new employee to a list of employees and update all of the sum functions below those employees. I've searched for a few days on this site and can't seem to find anyone who's having the same exact problem.
Once the employee's name and hours have been added in the new row, I need the subtotals at the bottom to include the new row in it's calculation of total hours.
I've looped down to the row using a for...next loop, with x changing.
I got as far as getting this to output into my sheet. It's logically correct, but doesn't actually work. It's just to give an idea of what I'm trying to do.
=SUM(Range(Cells(5, 17), Cells( x, 17)))
At the end I just want something like this to show up in the subtotal cell... =SUM(Q5:Q18)
Thank you so much!
回答1:
Try below code :
Sub sample()
dim x as Integer
For x = 5 To 17
Cells(x, 18) = WorksheetFunction.Sum(Range(Cells(5, 17), Cells(x, 17)))
Next
End Sub
OR
If you want to send formula as a string you can use the below.
Sub sample()
dim x as Integer
For x = 5 To 17
Cells(x, 18) = "=Sum(Q5:Q" & x & ")"
Next
End Sub
来源:https://stackoverflow.com/questions/16947648/how-to-output-the-sum-function-into-a-cell