user1805743
user1805743

Reputation: 1215

Return a string from a VBA function

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

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

Upvotes: 3

Views: 56485

Answers (2)

Jaime Jaimico
Jaime Jaimico

Reputation: 1

You need to do this

Public Function ExampleName() As String
  'code
End Function

You can put any of the available variables such as long, string, integer, etc...

Upvotes: 0

Shai Rado
Shai Rado

Reputation: 33692

You can use 2 ways to implement your "Hello World" example.

Option 1: Simple and good enough for your example, using a regular Sub :

Sub Hi_()

Dim HiStr   As String

HiStr = "Hello World"
MsgBox HiStr

End Sub

Option 2: Using a Function with "Hello World" example:

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

Upvotes: 9

Related Questions