我正在尝试使用VBA功能将所有功率结果加起来。
例如,如果我有6个收入,并且first=1
和last=5
,diff=5-1=4
,那么结果应该像total=6+6^2+6^3+6^4
。
下面是我的VBA代码,不知道为什么它不起作用,总是给我结果为0:
Function AC(last, first, revenue)
diff = last - firs
For i = 1 To diff
Count = revenue ^ i
Total = Total + Count
Next i
End Function
谢谢,如果有人可以帮助我
答案 0 :(得分:2)
您需要为函数赋值以使其返回值。您在diff = last - firs
上也有拼写错误:
Function AC(last, first, revenue)
diff = last - first
For i = 1 To diff
Count = revenue ^ i
Total = Total + Count
Next i
AC = Total
End Function
为了安全,还应该总是声明变量,我们可以对函数进行加法:
Option Explicit
Function AC(ByVal last As Long, ByVal first As Long, ByVal revenue As Double) As Double
Dim diff As Long
Dim i as long
Dim Count as Double
diff = last - first
For i = 1 To diff
Count = revenue ^ i
AC = AC + Count
Next i
End Function
答案 1 :(得分:0)
使用数组公式<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Service</title>
</head>
<body>
<img src="/views/assets/img/logo.png">
</body>
</html>
(AC = [sum(6 ^ row(1:4))]
的缩写为#
):
As Double
使用Excel公式:
Function AC#(last#, first#, revenue#)
AC = Evaluate("sum(" & revenue & " ^ row(1:" & last - first & "))")
End Function
答案 2 :(得分:0)
这是一个无循环的实现:
Function AC(last, first, revenue)
If revenue = 1 then AC = last - first: Exit Function
AC = revenue*((revenue^(last - first) - 1) / (revenue-1))
End Function