我在为excel编写函数时遇到错误。该函数的目的是向下查看表的整个日期列,并且对于该列中的每个匹配,从总值中减去该行的成本值(在相邻列中)。我在VBA中编写了一个函数,但是我甚至无法开始调试它,因为我遇到了第一个错误。错误显示“需要对象”并突出显示第一行,但似乎我正在将对象传递给函数(Ranges)。这是我的代码。
Public Function WeeklyAllowance(firstCell As Range, lastCell As Range)
Dim funds As Double
Dim today As Date
Dim thisWeekday As Integer
Dim earlierDay As Date
Set funds = 20
today = Now()
thisWeekday = Weekday(today)
earlierDay = today - thisWeekday + 1 'This should be sunday at first
Do Until earlierDay = today + 1 'Basically has one iteration for each day of the week until today
Dim cell, column As Range
Set column = Range(firstCell, lastCell)
For Each cell In column 'Iterate through the cells in the column and check the dates
If (cell.Value = earlierDay) Then
Dim cellCol, cellRow As Integer
cellCol = cell.column
cellRow = cell.Row
funds = funds - Sheet1.Cells(cellRow, cellCol + 1)
End If
Next cell
earlierDay = earlierDay + 1 'Increment the day to check
Loop
WeeklyAllowance = funds
End Function
有人可以帮我这个吗?
答案 0 :(得分:1)
Set funds = 20
是用于对象的语法。但是您已将上面定义的funds
定义为double
(它不是VBA
中的对象类型)。只需删除Set
关键字:
funds=20
答案 1 :(得分:0)
Dim cell, column As Range
错误。
Dim cell As Range, column As Range
如果您循环一周中的几天而不是添加1,那么请在工作日使用dateadd函数和参数。