从 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

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

Return a string from a VBA function

vba

提问by user1805743

I am following a tutorial and get a compile error at the hello world example function.

我正在学习教程并在 hello world 示例函数中遇到编译错误。

What's wrong here?

这里有什么问题?

enter image description here

在此处输入图片说明

Here is the code I tried:

这是我试过的代码:

Function hi()
    hi = "hello world"
End Function`

edit: suggested declarations didn't help enter image description here

编辑:建议的声明没有帮助 在此处输入图片说明

edit: getting closer. brackets seem to be a problem when calling "hi()" enter image description here

编辑:越来越近。调用“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 Functionwith "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 Subto 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