从 VBA 函数返回一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41141388/
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
Return a string from a VBA function
提问by user1805743
I am following a tutorial and get a compile error at the hello world example function.
我正在学习教程并在 hello world 示例函数中遇到编译错误。
What's wrong here?
这里有什么问题?
Here is the code I tried:
这是我试过的代码:
Function hi()
hi = "hello world"
End Function`
edit: suggested declarations didn't help
edit: getting closer. brackets seem to be a problem when calling "hi()"
回答by Shai Rado
You can use 2 ways to implement your "Hello Worls example.
您可以使用 2 种方法来实现您的“Hello Worls”示例。
Option 1:Simple and good enough for your example, using a regular Sub
:
选项 1:对于您的示例来说简单且足够好,使用常规Sub
:
Sub Hi_()
Dim HiStr As String
HiStr = "Hello World"
MsgBox HiStr
End Sub
Option 2:Using a Function
with "Hello World" example:
选项 2:使用Function
带有“Hello World”的示例:
Function Hi(TestHi As String) As String
' Input: this function receives a string as a parameter
' Output: returns a string
Hi = "Test Function with " & TestHi
End Function
Now we need a Sub
to test the Function
:
现在我们需要一个Sub
来测试Function
:
Sub Test_Hi_Function()
Dim TstHiFunc As String
' send "Hello World" to Function Hi as a parameter
' TstHiFunc gets the returnedstring result
TstHiFunc = Hi("Hello World")
' for debug only
MsgBox TstHiFunc
End Sub