gpt4 book ai didi

vba - 将变量传递给函数并返回 VBA

转载 作者:行者123 更新时间:2023-12-02 09:18:46 25 4
gpt4 key购买 nike

试图了解如何将值从函数传回子函数并在消息框中显示结果,但我无法理解。我错过了什么学习代码如下:-

Sub mySend()

Dim myNum As Integer

myNum = InputBox("Enter number")

myReturn (myNum)

msgbox myReturn 'would like to display result in messagebox here but no joy

End Sub
'--------------------------------------
Function myReturn(ByRef myNum As Integer)

Dim myCalc As Integer

myCalc = myNum + 10

myReturn = myCalc

End Function

最佳答案

不要使用 ByRef参数 - 只需正确使用函数。

Sub mySend()

Dim myNum As Integer

myNum = InputBox("Enter number")

myNum = myReturn(myNum) '// You need to assign (=) the value to the variable

msgbox myNum

End Sub
'--------------------------------------
Function myReturn(number As Integer) As Integer '// Note the return type after the ()

Dim myCalc As Integer

myCalc = number + 10

myReturn = myCalc

End Function

如果你想在你的例子中通过引用传递一个变量,那么你需要实际更改同一个变量的值,否则当你在调用代码中再次引用它时,该值不会改变:

(这是您修改的代码以在正确使用时显示 ByRef 的结果,我不建议实际使用此代码)
Sub mySend()

Dim myNum As Integer

myNum = InputBox("Enter number")

myReturn myNum '// No need for parentheses here

msgbox myNum

End Sub
'--------------------------------------
Function myReturn(ByRef myNum As Integer)

myNum = myNum + 10

End Function

关于vba - 将变量传递给函数并返回 VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44454796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com