excel - #价值!用户编写的时间加权平均函数返回的错误
问题描述
我正在尝试在 VBA 中编写一个计算时间加权平均值的函数,但是#VALUE!
当我尝试在工作表中使用该函数时出现错误。
在尝试调试时,我已经能够CurRPM
通过迭代CurOffset
和使用CurRng = rng.Offset(CurOffset, 0)
. 更改的效果CurRng
是向下迭代 RPM 列,检查下面的单元格CurRng
是否为空、与 相同CurRPM
或非空且与 不同CurRPM
。
Public Function TIMEAVERAGE(rng As Range) As Long
'Initializing Variables
Dim CurTime As Integer
Dim CurRPM As Integer
Dim CurSum As Integer
Dim CurOffset As Integer
CurOffset = 0
CurSum = 0
'The input cell is the first RPM
'The cell to the left of the input cell is the second RPM
CurTime = rng.Offset(0, -1)
CurRPM = rng
'Keep calculating as long as the cell below CurRng isn't empty
While IsEmpty(CurRng.Offset(1, 0)) = False
'If the cell below has the same RPM, look at next cell
If CurRng.Offset(1, 0) = CurRPM Then
CurOffset = CurOffset + 1
CurRng = rng.Offset(CurOffset, 0)
Else:
'Otherwise, add the previous RPM's contribution to the average
'CurTime, as shown, is the start of the previous RPM
CurSum = CurSum + CurRPM * (CurRng.Offset(0, -1) - CurTime)
'Change CurRPM and CurTime for the new RPM
CurRPM = CurRng.Offset(1, 0)
CurTime = CurRng.Offset(0, -1)
CurOffset = CurOffset + 1
CurRng = rng.Offset(CurOffset, 0)
End If
Wend
'Add the contributions of the final RPM
CurSum = CurSum + CurRPM * (CurRng.Offset(0, -1) - CurTime)
'Return the final TIMEAVERAGE
TIMEAVERAGE = CurSum / CurRng.Offset(0, -1)
End Function
如果用户输入下面的单元格,则此程序的预期结果将返回 150 =TIMEAVERAGE(B2)
。相反,#VALUE!
会返回一个错误。
A B
________________
1| Time | RPM
2| 0 | 100
3| 1 | 100
4| 2 | 100
5| 3 | 200
6| 4 | 200
7| 5 | 200
8| 6 | 200
解决方案
推荐阅读
- mysql - 加入最新值的数据表,如果没有找到显示空mysql?
- css - 如何删除背景视频的侧边栏并适合全屏
- algorithm - 如何在由升序数组和降序数组组成的数组中找到最大数
- acumatica - 移动到扩展库
- c++ - 何时忽略代码块以进行代码覆盖
- python - 如何使用request.Post在python中上传文件
- java - REST 调用调用 jax rs 和 Spring 中的另一个 REST 调用
- azure-web-app-service - Process.env.APPSEETING_MyAppSetting 在 Angular 8 中未定义为 Azure 上的 webAPP
- android - 如何使用詹金斯生成签名的应用程序包?
- android - 在尝试将 Android Emulator 连接到 MySql Server 时,我得到了 - java.sql.SQLNonTransientConnectionException: