3

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

5
  • either Function hi() As String , or you need to declare hi somewhere. Why do you need a Function ? why not a regular Sub ? Commented Dec 14, 2016 at 11:26
  • thanks Shai Rado. i am not yet selecting function or sub for a particular reason. first i need to find out how thy work :( see the edited original post, a added 2 images of my error Commented Dec 14, 2016 at 11:34
  • 1
    Calling a function with parenthesis will return an object, so it's expecting s=hi() or call hi to just run Commented Dec 14, 2016 at 11:37
  • thanks, i guess that's it. sorry for wasting your time on such stuff. Commented Dec 14, 2016 at 11:40
  • 1
    If you want to call your function from the Immediate pane and print the output then you need to call it like this : ? hi() (same as Debug.Print hi()) Commented Dec 14, 2016 at 17:32

2 Answers 2

9

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.