谁能告诉我为什么我得到#VALUE!使用此功能导致错误? 看起来很简单,但是我是VBA的新手,所以我不明白出了什么问题,尤其是当我没有从编译器收到任何错误时。
我试图在A列中选择年份,并让函数的值是从它右边开始的对角4个单元格的总和。
Function QTRtoANN(yearq As Range, age As Integer) As Double
Dim qtr1 As Double
Dim qtr2 As Double
Dim qtr3 As Double
Dim qtr4 As Double
Dim qtr1OS As Double
Dim qtr2OS As Double
Dim qtr3OS As Double
Dim qtr4OS As Double
qtr1OS = (age / 12) + 3 * ((age / 12) - 1)
qtr2OS = (age / 6) + 2 * ((age / 12) - 1)
qtr3OS = (age / 4) + ((age / 12) - 1)
qtr4OS = (age / 3)
qtr1 = Range(yearq).Offset(qtr1OS, 0).Value
qtr2 = Range(yearq).Offset(qtr2OS, -1).Value
qtr3 = Range(yearq).Offset(qtr3OS, -2).Value
qtr4 = Range(yearq).Offset(qtr4OS, -3).Value
QTRtoANN = qtr1 + qtr2 + qtr3 + qtr4
End Function
答案 0 :(得分:1)
主要问题是,从yearq
开始偏移时,您将否定参数(-1,-2,-3)用作 ColumnOffset 。通过快速阅读MSDN - Range.Offset
property,“正值向右偏移,负值向左偏移”。照原样,该代码正试图引用A列左侧的列,从而导致您的错误。
也如评论中所述:
yearq
已经是Range
,所以yearq.Offset...
age
不是12的倍数,则除法age/12
,age/6
等将不会得到整数,并且随后尝试进行Offset
会抛出一个错误。 我没有进行此更改,但是您可以Round
或将变量qtr1OS
,qtr2OS
等声明为Int
,以静默丢弃任何十进制值。因此,您修订后的Function
可能看起来像这样:
Function QTRtoANN(yearq As Range, age As Integer) As Double
Dim qtr1 As Double
Dim qtr2 As Double
Dim qtr3 As Double
Dim qtr4 As Double
Dim qtr1OS As Double
Dim qtr2OS As Double
Dim qtr3OS As Double
Dim qtr4OS As Double
qtr1OS = (age / 12) + 3 * ((age / 12) - 1)
qtr2OS = (age / 6) + 2 * ((age / 12) - 1)
qtr3OS = (age / 4) + ((age / 12) - 1)
qtr4OS = (age / 3)
qtr1 = yearq.Offset(qtr1OS, 0).Value
qtr2 = yearq.Offset(qtr2OS, 1).Value
qtr3 = yearq.Offset(qtr3OS, 2).Value
qtr4 = yearq.Offset(qtr4OS, 3).Value
QTRtoANN = qtr1 + qtr2 + qtr3 + qtr4
End Function