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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44454796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 12:43:04  来源:igfitidea点击:

Passing variable to function and back VBA

vba

提问by Junior

Trying to understand how to pass a value back from a function to a sub and display the result in a messagebox, but I can't get it. What am I missing Learning code below:-

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

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

回答by Sam

Don't use a ByRefparameter - just use a function properly.

不要使用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

If you want to pass a variable by reference in your example, then you need to actually change the value of that same variable otherwise when you reference it again in the calling code that value will not have changed:

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

(This is your code amended to show the result of ByRef when used properly, I don't recommend actually using this code)

(这是您修改的代码以在正确使用时显示 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

回答by Peter Schneider

Assign the result of the function to a variable and show the result in the messagebox:

将函数的结果分配给一个变量并在消息框中显示结果:

Dim result as Integer 
result = myReturn(myNum)

回答by HansZimmer5000

As Peter said, you need to save the result of your myReturn(myNum) call. And then show that variable:

正如彼得所说,您需要保存 myReturn(myNum) 调用的结果。然后显示该变量:

result = myReturn(myNum)
MsgBox result

Actually you don't even need the "Dim result". Why? I don't know, but I tested it and it worked.

实际上,您甚至不需要“昏暗的结果”。为什么?我不知道,但我测试了它并且它有效。