将VBA变量设置为来自字符串的函数的结果

时间:2019-04-09 05:51:01

标签: excel vba function

我今天读了很多关于函数的文章,它们似乎都处理数学/数字。我正在尝试使用一个函数,该函数返回一个字符串并将其捕获为“ main sub”中的变量,但是我无法使其正常工作。有人可以指出我在做什么错吗?

例如:

功能

Public Function Test(var) As Variant
 Bar = var & "World"
 MsgBox Bar
End Function

子:

Public Bar As Variant
Public Z As Variant
Sub testing()
 Call Test("Hello") ' This displays "HelloWorld" from MsgBox in Function 
 Test ("Hello")     ' This displays "HelloWorld" from MsgBox in Function 
 Z = Test("Hello")  ' This displays "HelloWorld" from MsgBox in Function 
 MsgBox Z           ' This displays an empty MsgBox :*(
End Sub

2 个答案:

答案 0 :(得分:4)

如果您希望函数返回值,请填充函数变量,然后将其返回到主子变量中,就像这样

Public Function Test(var As String) As String
    Test = var & " World"
End Function

Sub testing()
    returnstr  = Test("Hello")
    MsgBox returnstr
End Sub

答案 1 :(得分:2)

您没有从函数返回值。同样,函数仅应用于返回值,而不应执行更改事物(变量除外)或显示弹出窗口的操作。使用全局变量并将变量传递给函数也会使人困惑。您通常将局部变量传递给函数。这是一个更简洁的示例(按照常规惯例,首先使用您的主要功能):

Sub Testing()
    Dim Z As String
    Z = Test("Hello")
    MsgBox Z
    MsgBox Test("Hello")
End Sub

Public Function Test(ByRef var As String) As String
    Test = var & "World"
End Function