如何将一个函数的variables传递给另一个函数?

我正试图将一个函数的variables传递给另一个函数。

我的第一个想法是使用ByRef声明,我听到将在Visual Basic中通过引用传递参数。 但是,我不清楚如何使用它。 现在我有以下代码。

Function number(x As Double) As Double Dim z As Double z = 10.5 number = x End Function Function triple(ByRef z As Double) As Double z = z * 3 triple = z End Function 

可以说A1=2.5 。 如果我说B1=number(A1)那么答案是我预期的2.5。 然后我说B2=triple(B1)但答案是7.5而不是31.5。 我不知道为什么它取的是A1的值,而不是从函数number中取出variablesznumber

这是工作表的屏幕截图

在这里输入图像说明

提前致谢。

数字函数内的z在函数返回时已经消失了。 这个三重function就是把所通过的数字颠倒过来,2.5倍3就是你所看到的。 tipplefunction不知道z。 共享variables的一种方法是在函数之外声明它们。 Dim z为函数外部的两倍。 但是,如果你通过z作为b1的值是2.5那么你将得到相同的7.5只是调用三倍,不要通过b1的值

Dim z As Double

  Function tripple(x As Double) ' Use the value calculated from first function tripple = z * 3 End Function Function number(x As Double) ' Set the global variable ' May be some calculations are done and z is set z = 10.5 'Return x as in original code number = x End Function 

我不得不承认,我完全被你试图做的事所困惑。 我最初的想法是做类似于@dgortibuild议的事情,但是如果z从来没有被声明过,则会恢复到函数的input值。

不幸的是,VBA不支持可空双精度,据我所知,也不允许初始化全局variables。 这些function中的任何一个都可能不需要下面的zDeclaredvariables:

 Option Explicit Public z As Double Public zDeclared As Boolean Function number(x As Double) As Double z = 10.5 zDeclared = True number = x End Function Function triple(x As Double) As Double If zDeclared Then triple = z * 3 Else triple = x * 3 End If End Function 

CAVEAT:这可能不符合你的期望。 例如,如果您拨打电话number ,然后调用triple ,variablesz将被初始化。 如果您删除了调用number的函数,则可能希望triple恢复为input值 – 但不会。 现在做的是做的。

并且,以解释的方式,参数中的默认ByVal与可选的ByRef之间的区别在于, ByVal创build了参数值的新实例,而ByRef使用了现有的variables并因此保留对其的任何改变。 也许你已经理解了,但我认为值得澄清。

 Sub IncrementByVal(ByVal inp As Integer) inp = inp + 1 End Sub Sub IncrementByRef(ByRef inp As Integer) inp = inp + 1 End Sub Sub Test() Dim X As Integer X = 1 IncrementByVal X ' x is still 1 - the increment was for a locally scoped variable only IncrementByRef X ' x is now 2 End Sub