VBA里function sub
时间: 2023-10-04 11:07:30 浏览: 111
在VBA中,Function和Sub都是用于定义过程或函数的关键字。Function用于定义可以返回一个值的函数,而Sub用于定义无返回值的子过程。下面是一个简单的例子:
```
Function Sum(a As Integer, b As Integer) As Integer
Sum = a + b
End Function
Sub PrintSum()
Dim x As Integer
x = Sum(2, 3)
Debug.Print x
End Sub
```
在上面的代码中,Sum函数接收两个整数参数,并返回它们的和。PrintSum过程调用Sum函数,并将结果打印到调试窗口中。注意,函数的返回类型在声明时通过As关键字指定,而子过程则没有返回类型声明。
相关问题
VBA SUB和Function传值案例
当我们在 VBA 中编写 SUB 或 Function 时,我们可以传递参数来实现变量之间的值传递。下面是一个简单的案例:
```
Sub Main()
Dim num1 As Integer
Dim num2 As Integer
num1 = 10
num2 = 20
Call AddNumbers(num1, num2)
Debug.Print num1 '输出10
Debug.Print num2 '输出30
End Sub
Sub AddNumbers(ByVal x As Integer, ByRef y As Integer)
y = y + x
End Sub
```
在上面的代码中,我们定义了一个 Main 的 SUB,并且定义了两个整型变量 num1 和 num2,然后将 num1 和 num2 的值分别设置为 10 和 20。在 Main 中,我们调用了 AddNumbers 函数,并且将 num1 和 num2 作为参数传递给该函数。AddNumbers 函数是一个带有两个参数的 SUB,其中第一个参数 x 是一个 ByVal 参数,第二个参数 y 是一个 ByRef 参数。在函数中,我们将 y 的值加上了 x 的值。由于 y 是一个 ByRef 参数,所以在函数中更改 y 的值后,它的值也会在 Main 中被更改。因此,当我们在 Main 中输出 num1 和 num2 的值时,num1 的值仍为 10,而 num2 的值已经变为 30。
VBA SUB和Function来回传值案例
在 VBA 中,我们可以使用 SUB 和 Function 来实现变量值的来回传递。下面是一个简单的案例:
```
Sub Main()
Dim num1 As Integer
Dim num2 As Integer
Dim result As Integer
num1 = 10
num2 = 20
Call AddNumbers(num1, num2, result)
Debug.Print result '输出30
End Sub
Sub AddNumbers(ByVal x As Integer, ByVal y As Integer, ByRef z As Integer)
z = x + y
End Sub
```
在上面的代码中,我们定义了一个 Main 的 SUB,并且定义了三个整型变量 num1、num2 和 result,然后将 num1 和 num2 的值分别设置为 10 和 20。在 Main 中,我们调用了 AddNumbers 函数,并且将 num1 和 num2 作为参数传递给该函数,并将 result 作为 ByRef 参数传递。AddNumbers 函数是一个带有三个参数的 SUB,其中前两个参数 x 和 y 是 ByVal 参数,第三个参数 z 是一个 ByRef 参数。在函数中,我们将 x 和 y 的值相加,并将结果存储在 z 中。由于 z 是一个 ByRef 参数,所以我们可以在函数中更改 z 的值,并且该值会在 Main 中被保留。因此,当我们在 Main 中输出 result 的值时,该值为 30。
阅读全文
相关推荐
















