【发布时间】:2012-05-24 07:30:10
【问题描述】:
我正在尝试编写(我的第一个)自定义函数,该函数本质上将循环通过报告来总结未来 1、3、6 个月(等)内机器的成本
该函数返回值,但是,这些值不正确,并且在包含自定义函数的单元格上更成问题地 double 会更改使用自定义函数的周围单元格的值。
我正在处理的代码在这里:
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
单击一个单元格似乎会改变值,但没有可识别的顺序。
谷歌搜索并查看了here,但到目前为止似乎没有任何解决问题的方法。
任何帮助将不胜感激!
【问题讨论】:
标签: vba excel excel-2007 user-defined-functions