1

I've read a bunch about functions today and they all seem to deal with math/numbers. I'm trying to use a function which returns a string and capture that as a variable in the "main sub" but I can't get it to work. Can anybody point out what I'm doing wrong?

Eg:

Function:

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

Sub:

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 Answers 2

4

If you want the function to return a value, populate the function variable and return that in the main sub, like so

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

Sub testing()
    returnstr  = Test("Hello")
    MsgBox returnstr
End Sub
Sign up to request clarification or add additional context in comments.

Comments

3

You aren't returning a value from the function. Also, functions should only be used to return values, not to perform actions that change things (other than variables) or display pop-ups. It also gets confusing having global variables and passing variables to a function. You generally pass local variables to a function. Here's a cleaner example (with your main function first, as is normal convention):

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

8 Comments

I used the MsgBox for debug only, but I'm beginning to see my logic error thanks!
You're welcome. If an answer has answered your question sufficiently, please mark it as correct using the tick to the left. Otherwise you can leave a comment if you want more detail.
@TimStack, I accept an answer on 99% of my questions just not at work till tomorrow to test and verify. I'm leaning towards Error because he used a global variable but you code was also easy to read and helped me understand my issue. Thank you all rarely do I have such a hard time deciding between good answers!
Error used a function to modify a global variable, still without returning a value from the function. That's not how functions are supposed to be used. Functions are for returning values. If you only want to modify a global variable, then just use a Sub.
Functions absolutely can modify variables, both variables passed by reference and global variables, but if it isn't returning a value, then you just use a Sub.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.