我正在尝试编写(我的第一个)自定义函数,该函数将基本循环报告以在接下来的1,3,6个月(等等)中计算机器的成本
该函数返回值,但是,这些值不正确,并且在包含自定义函数的单元格上更加有问题的两倍会更改使用自定义函数的周围单元格的值。
我正在处理的代码在这里:
Option Explicit
Dim months As Integer 'a month is considered as 30 days
Dim cost As Long
Dim FleetData As Range
Dim rowCounter As Long
Dim lastRow As Long
Dim firstRow As Long
Dim component As Range
Dim dateOfAction As Range
Dim totalApprox As Range
Dim dateHorizon As Date 'Date to which the user wants to total the maintenance cost for
Private Function totalCosts(xMonths As Range)
'Dim totalCosts As Long
Application.Volatile
dateHorizon = Date + (30 * months)
firstRow = [A10].Row
rowCounter = firstRow
lastRow = Range("A65000").End(xlUp).Row
Set FleetData = [A10:S14]
If IsNumeric(xMonths.Value) Then months = xMonths.Value Else
If IsDate(xMonths.Value) Then months = (xMonths.Value - Date) / 30
cost = 0
Do While rowCounter < lastRow
Set component = Range(Cells(rowCounter, 1), Cells(rowCounter, 19))
Set dateOfAction = Cells(rowCounter, 7)
Set totalApprox = Cells(rowCounter, 12)
If dateOfAction <= dateHorizon Then
cost = cost + totalApprox
End If
totalCosts = cost
rowCounter = rowCounter + 1
Loop
End Function
我使用的数据是:
DateOfAction totalApprox
5/07/2014 $30,068.62
24/05/2005 $6,300.00
5/07/2012 $29,742.00
5/07/2012 $4,360.28
27/12/2012 $5,555.89
单击一个单元格似乎会改变值,但没有可识别的顺序。
用Google搜索并查看here但到目前为止似乎没有任何解决问题。
非常感谢任何帮助!
答案 0 :(得分:1)
要检查的一些提示和事项:
Range(...
和Cell(...
等不合格的引用是指活动工作表上的范围。如果数据表未激活,则此UDF将返回意外结果。请改用Worksheets("Sheet1").Range(...
之类的内容。但我再说一遍,将范围引用作为参数传递给函数是很多更好。months
。totalCosts = cost
)将无法正常工作。这在您提供的链接中有明确说明(您无法直接制作VBA UDF的第一点:列表)。另一方面,如果您从Sub
调用UDF并将该Sub作为宏运行,则将工作。如果您提供数据布局的完整详细信息以及如何使用UDF,我可以提供更具体的建议。