从 VBA 函数返回字符串

use*_*743 3 vba

我正在遵循教程并在 hello world 示例函数中收到编译错误。

这是怎么回事?

在此输入图像描述

这是我尝试过的代码:

Function hi()
    hi = "hello world"
End Function`
Run Code Online (Sandbox Code Playgroud)

编辑:建议的声明没有帮助 在此输入图像描述

编辑:越来越近。调用“hi()”时括号似乎是一个问题 在此输入图像描述

Sha*_*ado 7

您可以使用两种方法来实现“Hello World”示例。

选项 1:对于您的示例来说简单且足够好,使用常规Sub

Sub Hi_()

Dim HiStr   As String

HiStr = "Hello World"
MsgBox HiStr

End Sub
Run Code Online (Sandbox Code Playgroud)

选项 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
Run Code Online (Sandbox Code Playgroud)

现在我们需要一个Sub来测试Function

Sub Test_Hi_Function()

Dim TstHiFunc As String

' send "Hello World" to Function Hi as a parameter
' TstHiFunc gets the returned string result 
TstHiFunc = Hi("Hello World")

' for debug only
MsgBox TstHiFunc

End Sub
Run Code Online (Sandbox Code Playgroud)