How to return a result from a VBA function

0 votes

How do I return a result from a function?

For example:

Public Function test() As Integer
    return 1
End Function

This gives a compile error.

How do I make this function return an integer?

Nov 3 in Others by Kithuzzz
• 20,660 points
36 views

1 answer to this question.

0 votes

You must associate the value with the name of your function for non-object return types, like in:

Public Function test() As Integer
    test = 1
End Function

Example usage:

Dim i As Integer
i = test()

If the function returns an Object type, then you must use the Set keyword like this:

Public Function testRange() As Range
    Set testRange = Range("A1")
End Function

Example usage:

Dim r As Range
Set r = testRange()

Keep in mind that the execution of your function is not stopped by giving a return value to the function name. Exit Function must be stated specifically if you want to leave the function. For instance:

Function test(ByVal justReturnOne As Boolean) As Integer
    If justReturnOne Then
        test = 1
        Exit Function
    End If
    'more code...
    test = 2
End Function
answered Nov 4 by narikkadan
• 37,660 points

Related Questions In Others

0 votes
1 answer

What is a name function in JavaScript & how to define it?

A named function declares a name as ...READ MORE

answered Mar 7, 2019 in Others by Frankie
• 9,830 points
1,650 views
+2 votes
0 answers

Unable to return data to main function from promise

Hi, i am fairly new to node ...READ MORE

Sep 6, 2019 in Others by Muhammad Ahmed
• 140 points
246 views
0 votes
1 answer

How to create a function in Dart language?

Hi@akhtar, There are many function types available in ...READ MORE

answered Jul 22, 2020 in Others by MD
• 95,380 points
260 views
0 votes
1 answer

How to import data from a HTML table on a website to excel?

Hello  To import any HTML file in excel there ...READ MORE

answered Feb 10 in Others by gaurav
• 22,040 points
274 views
0 votes
1 answer

Convert image (jpg, png, jpeg) to base64

Try this - it will perform the ...READ MORE

answered Sep 24 in Others by narikkadan
• 37,660 points
76 views
0 votes
1 answer

Retrieve epay.info Balance with VBA and Excel

This code should log you in, provided ...READ MORE

answered Sep 5, 2018 in Blockchain by digger
• 26,720 points
449 views
0 votes
1 answer

How to load file to Excel Power query from SFTP site

Currently, I don't think there is a ...READ MORE

answered Dec 3, 2018 in Power BI by Upasana
• 8,620 points
2,199 views
0 votes
1 answer

Using VBA Excel to create a gramatically correct list

The Excel AND function is a logical ...READ MORE

answered Feb 9 in Others by gaurav
• 22,040 points
66 views
0 votes
1 answer
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP