我想创建一个函数,其中一个参数是所选内容下方的一个单元格。
我想将A、B相乘,并在B的单元格选择下方偏移一行。
Function MYFUNCTION(Num_1 As Integer, Num_2 As Integer) As Integer
Dim Num_3 As Integer
Num_3 = Range("Num_2").Offset(1, 0).Value
MYFUNCTION = Num_1 * Num_2 * Num_3
End Function
函数返回#VALUE!。
使用
Range
参数,而不是 Integer
s:
Public Function MyFunction(ByVal Num1 As Range, ByVal Num2 As Range) As Integer
Application.Volatile
MyFunction = Num1.Value * Num2.Value * Num2.Offset(1).Value
End Function
当
Application.Volatile
的值发生变化时,Num2.Offset(1)
(不幸的是)需要重新计算公式。
在这里使用
Integer
可能不是一个好主意。我建议 Double
,或者至少 Long
。
一开始就使用三个参数可能是个好主意。
此函数的另外两个变体:
Public Function MyFunction1(Num1 As Variant, Num2 As Range)
'remember to use two-cell range as a second argument
MyFunction1 = Num1 * Num2(1).Value * Num2(2).Value
End Function
Public Function MyFunction2(Num1 As Variant, Num2 As Variant)
'remember to use two-cell range as a second argument
MyFunction2 = WorksheetFunction.Product(Num1, Num2)
End Function
使用:
=MyFunction1(B5, C2:C3)
或=MyFunction2(5, C2:C3)
在这两种情况下,最后两个因素都作为一个参数引用:双单元格范围。这避免了使用
Volatile
语句。两种变体之间的差异在于第三个因素的缺失或变化的结果。
在
MyFunction1
中,如果第二个参考仅针对一个单元格,则结果是正确的,但如果第三个因素发生变化,则不会重新计算。如果第三个因素的单元格为空,则结果为 0。
在
MyFunction2
中,如果第二个引用仅针对一个单元格,或者第三个因子的单元格为空,则结果是两个因子的乘积。