VBA 新手并尝试创建带有偏移引用的新函数

问题描述 投票:0回答:1

使用 Excel 2019

我想创建一个函数,其中参数之一是所选内容之一下方的一个单元格,我不知道该怎么做。

我想要一个将 A 和 B 相乘的函数,AND 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!。

显然...不起作用。

其他关于如何创建“自己的”A*B 函数的视频很少,没有关于使用 VBA 创建高级函数的视频(澄清一下,我不是在谈论子例程)

excel vba user-defined-functions offset excel-2019
1个回答
1
投票

使用

Range
参数,而不是
Integer

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

© www.soinside.com 2019 - 2024. All rights reserved.