Skip to content
Fix Code Error

How to return a result from a VBA function

March 13, 2021 by Code Error
Posted By: Anonymous

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?

Solution

For non-object return types, you have to assign the value to the name of your function, like this:

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

Note that assigning a return value to the function name does not terminate the execution of your function. If you want to exit the function, then you need to explicitly say Exit Function. For example:

Function test(ByVal justReturnOne As Boolean) As Integer
    If justReturnOne Then
        test = 1
        Exit Function
    End If
    'more code...
    test = 2
End Function

Documentation: http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx

Answered By: Anonymous

Related Articles

  • Is CSS Turing complete?
  • Maven2: Missing artifact but jars are in place
  • Form field border-radius is not working only on the…
  • Search match multiple values in single field in…
  • How to parse deserialized object back into arrays?
  • In custom class when calling a=s+b causing s (or b)…
  • Write Datatable to a Excel file
  • How to concatenate cell values until it finds a…
  • How to avoid using Select in Excel VBA
  • How to use Regular Expressions (Regex) in Microsoft…
  • Vue custom directive uses the updated Dom (or $el)
  • Run calculation on Array in VBA - across columns
  • What's the difference between eval, exec, and compile?
  • VBA get a list of files in folder and their tags (Keywords)
  • List(of String) or Array or ArrayList
  • Parsing JSON in Excel VBA
  • error LNK2005: ✘✘✘ already defined in…
  • error: resource android:attr/fontVariationSettings not found
  • How to loop through a column to copy all matching…
  • VBA error 1004 - select method of range class failed
  • lists and arrays in VBA
  • Use getElementById on HTMLElement instead of HTMLDocument
  • Callback functions in C++
  • Split cell value that based on a delimiter and…
  • VBA (Excel) Initialize Entire Array without Looping
  • Function is Producing an Compile Erorr
  • How to Insert cell reference in VBA code for…
  • Getting around the Max String size in a vba function?
  • Is there a way to crack the password on an Excel VBA…
  • How to make Lodash orderBy to sort only the records…
  • Automatic date update in a cell when another cell's…
  • VBA Excel 2-Dimensional Arrays
  • Show scroll update when scrolling down page
  • Importing Excel spreadsheet data into another Excel…
  • Copy data from non-contiguous cells
  • AppCompat v7 r21 returning error in values.xml?
  • Trying to Add One further condition to Function
  • Adds a comment if range of cell equals to range of…
  • Paste Excel range in Outlook
  • What are the currently supported CSS selectors…
  • How to read a file and write into a text file?
  • Excel VBA Password via Hex Editor
  • Excel VBA - How to Redim a 2D array?
  • Where and why do I have to put the "template" and…
  • What is an optional value in Swift?
  • Why after set mapping, index return nothing?
  • Android- Error:Execution failed for task…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Smart way to truncate long strings
  • VBA for loop on unique ID
  • How do i fix Outlook VBA Compile Error Type Mismatch
  • What does "Fatal error: Unexpectedly found nil while…
  • Attempting to adapt existing code that opens Excel…
  • I want to create a SQLite database like in the…
  • Create Event handles dynamically using variable as…
  • Angular: Can't find Promise, Map, Set and Iterator
  • Loop through multiple files in a folder a copy and…
  • useEffect Error: Minified React error #321 (GTM…
  • Getting the closest string match
  • All com.android.support libraries must use the exact…
  • Change column type in pandas
  • Slow VBA loop for hiding rows
  • How do I copy a range of formula values and paste…
  • Checking if a variable is an integer in PHP
  • VBA Print to PDF and Save with Automatic File Name
  • Returning a regex match in VBA (excel)
  • Excel VBA - Separate data by pattern by using Split Function
  • How do I return the response from an asynchronous call?
  • Fastest way to list all primes below N
  • How can i check if file is empty?
  • How to get logged-in user's name in Access vba?
  • What are the undocumented features and limitations…
  • What is a NullReferenceException, and how do I fix it?
  • How to search a string in a single column (A) in…
  • How store a range from excel into a Range variable?
  • Save attachments to a folder and rename them
  • HTTP 415 unsupported media type error when calling…
  • Running same VBA code for a range of columns (one…
  • "Could not find acceptable representation" using…
  • ByRef argument type mismatch in Excel VBA
  • Unexpected end of JSON input while parsing
  • Python list processing
  • Excel VBA For Each Worksheet Loop
  • How to check If every Cell in Range found on another…
  • Application.WorksheetFunction.Match method
  • Extract values from CSV and put it into an Excel sheet
  • How to fill color in a cell in VBA?
  • Insert Multiple Shapes based on cell value
  • VBA EntireRow.Delete until specific Column
  • VBA for filtering columns
  • Loop through different ranges with variable bounds
  • Java finished with non-zero exit value 2 - Android Gradle
  • Convert Multiple Excel Sheet Ranges as PDF VBA
  • Find row number of matching value
  • Excel VBA: AutoFill Multiple Cells with Formulas
  • Adding condition to existing function
  • Find values in TXT file and replace with values from…
  • Copy from one workbook and paste into another
  • Change HTML email body font type and size in VBA
  • How to copy data into cells, make a table and add…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Run cURL commands from Windows console

Next Post:

HTML table with 100% width, with vertical scroll inside tbody

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error