[英]New to VBA in Excel. Trying to sum an incremented function
So what I am trying to do is take the difference between two values(x) and (y) to get (n).所以我想做的是取两个值(x)和(y)之间的差来得到(n)。 I then want to run (x) through a formula (n) times incrementing (x) each time.
然后我想通过公式 (n) 运行 (x) 次,每次递增 (x)。 Then I want to output the sum all of those results into a cell.
然后我想 output 将所有这些结果的总和放入一个单元格中。 Cant figure out how to do it neatly within one cell like normal, so I've turned to VBA for once.
无法弄清楚如何像平常一样在一个单元格内整齐地完成它,所以我曾经转向 VBA 一次。
Here is what I have so far:这是我到目前为止所拥有的:
Sub Math()
'
'Math
'
Dim i As Integer
i = 0
Do While i < ((E42) - (d42))
cell(h42).Value = ((((d42) + i) ^ 2) * 100) / 3
End Sub
What I'm stuck on is how to get the result of each loop and sum them all together.我坚持的是如何获得每个循环的结果并将它们加在一起。 I expect to have an i value that can range anywhere from 1-100.
我希望 i 值可以在 1-100 之间。 The only way I can think that would definitely work is messy where i would have a large number of cells in a column set aside that will calculate each of the iterations individually, then sum all of those together.
我认为肯定会起作用的唯一方法是混乱的,我将在一列中留出大量单元格,这些单元格将单独计算每个迭代,然后将所有这些加在一起。
Alternatively, if theres a way to write a function that can calculate the sum(n) of ((x+n)^2)*100/3 then that would be much nicer but I cant think of how it would be written.或者,如果有一种方法可以编写一个 function 可以计算 ((x+n)^2)*100/3 的 sum(n),那会更好,但我想不出它会如何写。
Here is how you can make a function (which can be used directly in worksheet formulas) to form a sum:以下是如何使 function(可直接在工作表公式中使用)形成总和:
Function eval_sum(n As Long, x As Double) As Double
Dim s As Double, i As Long
For i = 0 To n - 1
s = s + (x + i) ^ 2
Next i
eval_sum = s * 100 / 3
End Function
This function evaluates:这个 function 评估:
100/3 * (x^2 + (x+1)^2 + (x+2)^2 + ... + (x+(n-1))^2)
It wasn't completely clear if this is what you were trying to do.目前尚不完全清楚这是否是您想要做的。 If not, you can tweak the code to fit your needs.
如果没有,您可以调整代码以满足您的需求。
Small point: I used Long
rather than Integer
.小点:我使用
Long
而不是Integer
。 Forget that Integer
exists.忘记
Integer
存在。 It is really legacy from the days of limited memory and 16-bit computers.它确实是从有限的 memory 和 16 位计算机时代遗留下来的。 In modern Excel an
Integer
is stored with 32 bits anyway.在现代 Excel 中,
Integer
无论如何都以 32 位存储。 You are just risking overflow for no good reason.您只是无缘无故地冒着溢出的风险。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.