How to return in excel

Содержание

  1. How to return value from a function in Excel using VBA – Excelchat
  2. Return a value using exit function or End function
  3. Instant Connection to an Expert through our Excelchat Service
  4. How to Return Cell Address Instead of Value in Excel (Easy Formula)
  5. Lookup And Return Cell Address Using the ADDRESS Function
  6. Lookup And Return Cell Address Using the CELL Function
  7. How can I return the results of a function to a cell in Excel?
  8. 4 Answers 4
  9. Related
  10. Hot Network Questions
  11. Subscribe to RSS
  12. VBA Function – Call, Return Value, & Parameters
  13. Creating a Function without Arguments
  14. Calling a Function from a Sub Procedure
  15. Creating Functions
  16. Single Argument
  17. Multiple Arguments
  18. Optional Arguments
  19. VBA Coding Made Easy
  20. Default Argument Value
  21. ByVal and ByRef
  22. Exit Function
  23. Using a Function from within an Excel Sheet
  24. VBA Code Examples Add-in

How to return value from a function in Excel using VBA – Excelchat

In Excel VBA , we can use function when we are performing repetitive tasks like data formatting, calculations and so on. With Excel VBA, we can create a function that returns a value when the function is used. This article looks at how to return a value from a function using VBA Excel .

Figure 1: Return value function with VBA

Return a value using exit function or End function

When conducting a function procedure , you need to assign a value to the procedure’s name . After you have assigned the name, you will have the value that was most recently assigned to the procedure returned when an Exit or End function is executed.

Note that with VBA, we can have more than one Exit function statement as well as mix Return and Exit function statement in same procedure.

Instant Connection to an Expert through our Excelchat Service

Most of the time, the problem you will need to solve will be more complex than a simple application of a formula or function. If you want to save hours of research and frustration, try our live Excelchat service! Our Excel Experts are available 24/7 to answer any Excel question you may have. We guarantee a connection within 30 seconds and a customized solution within 20 minutes.

Источник

How to Return Cell Address Instead of Value in Excel (Easy Formula)

When using lookup formulas in Excel (such as VLOOKUP, XLOOKUP, or INDEX/MATCH), the intent is to find the matching value and get that value (or a corresponding value in the same row/column) as the result.

But in some cases, instead of getting the value, you may want the formula to return the cell address of the value.

This could be especially useful if you have a large data set and you want to find out the exact position of the lookup formula result.

There are some functions in Excel that designed to do exactly this.

In this tutorial, I will show you how you can find and return the cell address instead of the value in Excel using simple formulas.

This Tutorial Covers:

Lookup And Return Cell Address Using the ADDRESS Function

The ADDRESS function in Excel is meant to exactly this.

It takes the row and the column number and gives you the cell address of that specific cell.

Below is the syntax of the ADDRESS function:

  • row_num: Row number of the cell for which you want the cell address
  • column_num: Column number of the cell for which you want the address
  • [abs_num]: Optional argument where you can specify whether want the cell reference to be absolute, relative, or mixed.
  • [a1]: Optional argument where you can specify whether you want the reference in the R1C1 style or A1 style
  • [sheet_text]: Optional argument where you can specify whether you want to add the sheet name along with the cell address or not

Now, let’s take an example and see how this works.

Suppose there is a dataset as shown below, where I have the Employee id, their name, and their department, and I want to quickly know the cell address that contains the department for employee id KR256.

Below is the formula that will do this:

In the above formula, I have used the MATCH function to find out the row number that contains the given employee id.

And since the department is in column C, I have used 3 as the second argument.

This formula works great, but it has one drawback – it won’t work if you add the row above the dataset or a column to the left of the dataset.

This is because when I specify the second argument (the column number) as 3, it’s hard-coded and won’t change.

In case I add any column to the left of the dataset, the formula would count 3 columns from the beginning of the worksheet and not from the beginning of the dataset.

So, if you have a fixed dataset and need a simple formula, this will work fine.

But if you need this to be more fool-proof, use the one covered in the next section.

Lookup And Return Cell Address Using the CELL Function

While the ADDRESS function was made specifically to give you the cell reference of the specified row and column number, there is another function that also does this.

It’s called the CELL function (and it can give you a lot more information about the cell than the ADDRESS function).

Below is the syntax of the CELL function:

  • info_type: the information about the cell you want. This could be the address, the column number, the file name, etc.
  • [reference]: Optional argument where you can specify the cell reference for which you need the cell information.

Now, let’s see an example where you can use this function to look up and get the cell reference.

Suppose you have a dataset as shown below, and you want to quickly know the cell address that contains the department for employee id KR256.

Below is the formula that will do this:

The above formula is quite straightforward.

I have used the INDEX formula as the second argument to get the department for the employee id KR256.

And then simply wrapped it within the CELL function and asked it to return the cell address of this value that I get from the INDEX formula.

Now here is the secret to why it works – the INDEX formula returns the lookup value when you give it all the necessary arguments. But at the same time, it would also return the cell reference of that resulting cell.

In our example, the INDEX formula returns “Sales” as the resulting value, but at the same time, you can also use it to give you the cell reference of that value instead of the value itself.

Normally, when you enter the INDEX formula in a cell, it returns the value because that is what it’s expected to do. But in scenarios where a cell reference is required, the INDEX formula will give you the cell reference.

In this example, that’s exactly what it does.

And the best part about using this formula is that it is not tied to the first cell in the worksheet. This means that you can select any data set (which could be anywhere in the worksheet), use the INDEX formula to do a regular look up and it would still give you the correct address.

And if you insert an additional row or column, the formula would adjust accordingly to give you the correct cell address.

So these are two simple formulas that you can use to look up and find and return the cell address instead of the value in Excel.

I hope you found this tutorial useful.

Other Excel tutorials you may also like:

Источник

How can I return the results of a function to a cell in Excel?

Suppose I have a function attached to one of my Excel sheets:

How can I get the results of foo returned to a cell on my sheet? I’ve tried «=foo(10)» , but all it gives me is «#NAME?»

I’ve also tried =[filename]!foo(10) and [sheetname]!foo(10) with no change.

4 Answers 4

Try following the directions here to make sure you’re doing everything correctly, specifically about where to put it. ( Insert->Module )

I can confirm that opening up the VBA editor, using Insert->Module , and the following code:

and on a sheet putting «=TimesTwo(100)» into a cell gives me 200 .

Put the function in a new, separate module (Insert->Module), then use =foo(10) within a cell formula to invoke it.

Where did you put the «foo» function? I don’t know why, but whenever I’ve seen this, the solution is to record a dimple macro, and let Excel create a new module for that macro’s code. Then, put your «foo» function in that module. Your code works when I follow this procedure, but if I put it in the code module attached to «ThisWorkbook,» I get the #NAME result you report.

include the file name like this

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.17.43323

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

VBA Function – Call, Return Value, & Parameters

In this Article

This tutorial will teach you to create and use functions with and without parameters in VBA

VBA contains a large amount of built-in functions for you to use, but you are also able to write your own. When you write code in VBA, you can write it in a Sub Procedure, or a Function Procedure. A Function Procedure is able to return a value to your code. This is extremely useful if you want VBA to perform a task to return a result. VBA functions can also be called from inside Excel, just like Excel’s built-in Excel functions.

Creating a Function without Arguments

To create a function you need to define the function by giving the function a name. The function can then be defined as a data type indicating the type of data you want the function to return.

You may want to create a function that returns a static value each time it is called – a bit like a constant.

If you were to run the function, the function would always return the value of 50.

You can also create functions that refer to objects in VBA but you need to use the Set Keyword to return the value from the function.

If you were to use the above function in your VBA code, the function would always return the range of cells A1 to G4 in whichever sheet you are working in.

Calling a Function from a Sub Procedure

Once you create a function, you can call it from anywhere else in your code by using a Sub Procedure to call the function.

The value of 50 would always be returned.

You can also call the GetRange function from a Sub Procedure.

In the above example, the GetRange Function is called by the Sub Procedure to bold the cells in the range object.

Creating Functions

Single Argument

You can also assign a parameter or parameters to your function. These parameters can be referred to as Arguments.

We can then call the above function from a Sub Procedure in order to work out how many pounds a specific amount of kilos are.

A function can be a called from multiple procedures within your VBA code if required. This is very useful in that it stops you from having to write the same code over and over again. It also enables you to divide long procedures into small manageable functions.

In the above example, we have 2 procedures – each of them are using the Function to calculate the pound value of the kilos passed to them in the dblKilo Argument of the function.

Multiple Arguments

You can create a Function with multiple arguments and pass the values to the Function by way of a Sub Procedure.

We can then call the function to calculate the amount of days between 2 dates.

Optional Arguments

You can also pass Optional arguments to a Function. In other words, sometimes you may need the argument, and sometimes you may not – depending on what code you are using the Function with .

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Default Argument Value

You can also set the default value of the Optional arguments when you are creating the function so that if the user omits the argument, the value that you have put as default will be used instead.

ByVal and ByRef

When you pass values to a function, you can use the ByVal or ByRef keywords. If you omit either of these, the ByRef is used as the default.

ByVal means that you are passing a copy of the variable to the function, whereas ByRef means you are referring to the original value of the variable. When you pass a copy of the variable (ByVal), the original value of the variable is NOT changed, but when you reference the variable, the original value of the variable is changed by the function.

In the function above, the ByRef could be omitted and the function would work the same way.

To call this function, we can run a sub-procedure.

Note that the debug windows show the value 40 both times. When you pass the variable IntVal to the function – the value of 10 is passed to the function, and multiplied by 4. Using the ByRef keyword (or omitting it altogether), will AMEND the value of the IntVal variable. This is shown when you show first the result of the function in the immediate window (40), and then the value of the IntVal variable in the debug window (also 40).

If we do NOT want to change the value of the original variable, we have to use ByVal in the function.

Now if we call the function from a sub-procedure, the value of the variable IntVal will remain at 10.

Exit Function

If you create a function that tests for a certain condition, and once the condition is found to be true, you want return the value from the function, you may need to add an Exit Function statement in your Function in order to exit the function before you have run through all the code in that function.

The function above will loop through the string that is provided until it finds a number, and then return that number from the string. It will only find the first number in the string as it will then Exit the function.

The function above can be called by a Sub routine such as the one below.

Using a Function from within an Excel Sheet

In addition to calling a function from your VBA code using a sub procedure, you can also call the function from within your Excel sheet. The functions that you have created should by default appear in your function list in the User Defined section of the function list.

Click on the fx to show the Insert Function dialog box.

Select User Defined from the Category List

Select the function you require from the available User Defined Functions (UDF’s).

Alternatively, when you start writing your function in Excel, the function should appear in the drop down list of functions.

If you do not want the function to be available inside an Excel sheet, you need to put the Private word in front of the word Function when you create the function in your VBA code.

It will now not appear in the drop down list showing the Excel functions available.

Interestingly enough, however, you can still use the function – it just will not appear in the list when looking for it!

If you have declared the second argument as Optional, you can omit it within the Excel sheet as well as within the VBA code.

You can also use the a function that you have created without arguments in your Excel sheet.

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Contents

  • 1 What is the return character in Excel?
  • 2 How do you return in a cell worksheet?
  • 3 How do I return the contents of a cell in Excel?
  • 4 How do I return the number of characters in Excel?
  • 5 What is char 34 Excel?
  • 6 How do I use carriage return as delimiter in Excel?
  • 7 How do you skip lines in sheets?
  • 8 How do you enter in a spreadsheet?
  • 9 How do I return text in Excel formula?
  • 10 How do I return text value to a cell?
  • 11 How do I return a column letter in Excel?
  • 12 How do I extract the first letter in Excel?
  • 13 How do I return text between two characters in Excel?
  • 14 How do I extract one letter from a cell in Excel?
  • 15 How do I find char 13 in Excel?
  • 16 How do you remove quotation marks in Excel?
  • 17 What is CHR 13?
  • 18 What does CTRL J do in excel?
  • 19 What does carriage return do?
  • 20 What does Ctrl R do in Google Sheets?

What is the return character in Excel?

The Excel CHAR function returns a character when given a valid character code. CHAR can be used to specify characters that are hard to enter in a formula. For example, CHAR(10) returns a line break, and can be used to add a line break to text in a formula.

How do you return in a cell worksheet?

Carriage Return (Hard Return)
While typing in a spreadsheet cell, hold down the command key while you press the enter key. This will force the cursor to the next line. Holding down command enter a second time will create the extra line after each paragraph within the cell.

How do I return the contents of a cell in Excel?

Get cell content at given row and column

  1. =ADDRESS(1,1)
  2. =INDIRECT(“$C$9”)
  3. =INDEX(A1:E100,G4,G5)

How do I return the number of characters in Excel?

To use the function, enter =LEN(cell) in the formula bar and press Enter. In these examples, cell is the cell you want to count, such as B1. To count the characters in more than one cell, enter the formula, and then copy and paste the formula to other cells.

What is char 34 Excel?

You can also insert a double quote in an Excel formula using the CHAR function. The CHAR function takes the ASCII value and returns the corresponding character value. The ASCII value for a double quote is 34.

How do I use carriage return as delimiter in Excel?

(To do an in-cell carriage return in the first place, you just hit Alt+Enter.) Highlight your column of data, making sure the columns to its right are empty. On the Data ribbon, hit Text to Columns. Hit the Delimited option, and then check the Other option.

How do you skip lines in sheets?

Below are the steps to use this in a cell to go to a new line:

  1. Double-click on the cell in which you want to add a line break (or select it and then press F2).
  2. Place the cursor where you want to insert the line break.
  3. Hold the ALT key and then press the Enter key (or Control + Option + Enter if you’re using a Mac)

How do you enter in a spreadsheet?

Enter text or a number in a cell

  1. On the worksheet, click a cell.
  2. Type the numbers or text that you want to enter, and then press ENTER or TAB. To enter data on a new line within a cell, enter a line break by pressing ALT+ENTER.

How do I return text in Excel formula?

When given the reference of a cell that contains a formula, it will return the entire formula as text. In the example as show, the formula: =FORMULATEXT(C5) returns the text “=IF(…

How do I return text value to a cell?

Returns “-” at the end of the text value if the cell is formatted in color for negative values. Returns “()” at the end of the text value if the cell is formatted with parentheses for positive or all values.
CELL format codes.

If the Excel format is The CELL function returns
General “G”
0 “F0”
#,##0 “,0”
0.00 “F2”

How do I return a column letter in Excel?

To convert a column number to an Excel column letter (e.g. A, B, C, etc.) you can use a formula based on the ADDRESS and SUBSTITUTE functions. With this information, ADDRESS returns the text “A1”.

Extract first n characters from string
Select a blank cell, here I select the Cell G1, and type this formula =LEFT(E1,3) (E1 is the cell you want to extract the first 3 characters from), press Enter button, and drag fill handle to the range you want. Then you see the first 3 characters are extracted.

How do I return text between two characters in Excel?

To extract part string between two different characters, you can do as this: Select a cell which you will place the result, type this formula =MID(LEFT(A1,FIND(“>”,A1)-1),FIND(“<«,A1)+1,LEN(A1)), and press Enter key. Note: A1 is the text cell, > and < are the two characters you want to extract string between.

  1. Select the cells that you want to extract substring between characters, click Kutools > Text > Extract Text.
  2. 2.In the popping Extract Text dialog, under Extract by rule tab, go to the Text section, type the characters that you want to extract string between, and the string can be repented by the wildcard *.

How do I find char 13 in Excel?

If that extra character is not a ASCII 13, you can use the function =Code(AString) to get the code of the left most character of a string. If you press Ctrl + J while in the Find dialog, you will be able to search for those characters.

How do you remove quotation marks in Excel?

Here is what you have to do:

  1. Open the file and select all columns or rows from which you want to remove the quotes.
  2. Open the “Find and Replace” function by holding Ctrl + F on your keyboard.
  3. Select the function and a dialog box will appear.
  4. Click the “Replace All” button if you want to delete all quotation marks.

What is CHR 13?

What is Chr(13) The ASCII character code 13 is called a Carriage Return or CR . On windows based computers files are typically delimited with a Carriage Return Line Feed or CRLF .

What does CTRL J do in excel?

What is Ctrl J in Excel? So, instead of the ALT+Enter shortcut we need to enter CTRL+J, this is the shortcut to the line break which is character 10 in the ASCII control code. You can search for line breaks using this shortcut instead. So if we want to find and place out line breaks with a space.

What does carriage return do?

In computing, the carriage return is one of the control characters in ASCII code, Unicode, EBCDIC, and many other codes. It commands a printer, or other output system such as the display of a system console, to move the position of the cursor to the first position on the same line.

What does Ctrl R do in Google Sheets?

Add or Change Rows and Columns on a PC
Ctrl+R: Duplicate the data from the first row of the selected range to the right. Ctrl+Enter: Duplicate the data from the first cell of the selected range into the other cells. Ctrl+Alt+9: Hide rows.

Just setting the return value to the function name is still not exactly the same as the Java (or other) return statement, because in java, return exits the function, like this:

public int test(int x) {
    if (x == 1) {
        return 1; // exits immediately
    }

    // still here? return 0 as default.
    return 0;
}

In VB, the exact equivalent takes two lines if you are not setting the return value at the end of your function. So, in VB the exact corollary would look like this:

Public Function test(ByVal x As Integer) As Integer
    If x = 1 Then
        test = 1 ' does not exit immediately. You must manually terminate...
        Exit Function ' to exit
    End If

    ' Still here? return 0 as default.
    test = 0
    ' no need for an Exit Function because we're about to exit anyway.
End Function 

Since this is the case, it’s also nice to know that you can use the return variable like any other variable in the method. Like this:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test <> 1 Then ' Test the currently set return value
        test = 0 ' Reset the return value to a *new* value
    End If

End Function 

Or, the extreme example of how the return variable works (but not necessarily a good example of how you should actually code)—the one that will keep you up at night:

Public Function test(ByVal x As Integer) As Integer

    test = x ' <-- set the return value

    If test > 0 Then

        ' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
        ' AND THE RESULT RESETTING THE RETURN VALUE.
        test = test(test - 1)

    End If

End Function

VBA Return

VBA Return Statement

In this article, we will see an outline on Excel VBA Return. It is a statement in VBA which is used for the user-defined functions with the GoSub statement. This statement can also be used outside of a subprocedure when we are using a user-defined function. And when we are using the GoSub statement with the return statement then both GoSub and return statements should be in the same procedure. Now let us discuss what the difference between these two procedures is. First, we will begin with the GoSub statement. In this statement, we stay in the same procedure but move to another statement and get a result with some lines execution of code and then return to the original procedure.

The next is the use of the return statement in a user-defined function. In the user-defined function, a function is created which is returns a value through return statement. We will discuss both types of use of the return statement through some examples.

How to Use Go Sub Return Statement in VBA?

We will learn how to use Go Sub Return Statement in Excel by using the VBA Code.

You can download this VBA Return Excel Template here – VBA Return Excel Template

Example #1 – VBA Return Statement

Let us first discuss how Return with GoSub Statement works in VBA. How do we execute them and what we will learn in this example?. For this, follow the below steps:

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Once we have a module in the Editor now let us begin with the procedure of declaring a sub-function.

Code:

Sub Example1()

End Sub

VBA Return Example 1-1

Step 3: Now let us send the execution to another line by the GoSub Statement but within the same procedure.

Code:

Sub Example1()

GoSub Sample

End Sub

VBA Return Example 1-2

Step 4: Now let us exit the subprocedure, for now, let us keep this in mind exit sub and end sub are two different.

Code:

Sub Example1()

GoSub Sample
Exit Sub

End Sub

Exit Sub Example 1-3

Step 5: Now we can perform some execution of lines of code for the subroutine.

Code:

Sub Example1()

GoSub Sample
Exit Sub
Sample:
MsgBox "This is a sample document"

End Sub

VBA Return Example 1-4

Step 6: Now we will use the return statement to move back to the original procedure.

Code:

Sub Example1()

GoSub Sample
Exit Sub
Sample:
MsgBox "This is a sample document"
Return

End Sub

VBA Return Example 1-5

Step 7: When we press F8 we can see how this procedure works step by step.

VBA Return Example Output 1

Now we can see in the steps that process moved to the line of Sample subroutine when the compiler was on the Gosub Statement and it again moved back to exit sub after giving us the result to Exit substatement.

Example #2 – VBA Return Statement

In the above example, we use a single subroutine and what happens if there are multiple subroutines with multiple GoSub and multiple Return statements. Let us find out in example 2. For this, follow the below steps:

Step 1: We will proceed with the same module just with another subprocedure.

Code:

Sub Example2()

End Sub

VBA Return Example 2-1

Step 2: Similar to above let us declare multiple subroutines with the GoSub statement.

Code:

Sub Example2()

GoSub Sample1
GoSub Sample2

End Sub

Multiple Subroutines Example 2-2

Step 3: Now let us exit the sub and define what those subroutines will do.

Code:

Sub Example2()

GoSub Sample1
GoSub Sample2
Exit Sub
Sample1:
MsgBox "This is first Execution"
Return
Sample2:
MsgBox "This is second Execution"
Return

End Sub

VBA Return Example 2-3

Step 4: Run this code by hitting F5 or Run button.

VBA Return Example Output 2

In this example, Code worked in the same way, the compiler went to GoSub Sample1 and executed the lines of code for sample1 then it returned it to GoSub Sample2 and then again went to execute the lines of code for sample2 and then the return statement took it back to the exit substatement.

Example #3 – VBA Return Statement

Let us use a somewhat realistic example for the GoSub statement such as for addition. For this, follow the below steps:

Step 1: Declare a subprocedure for example 3.

Code:

Sub Example3()

End Sub

VBA Return Example 3-1

Step 2: Define two integer variables and ask the user to provide input as integers.

Code:

Sub Example3()

Dim i As Integer, b As Integer
i = InputBox("Enter first number")
b = InputBox("Enter second number")

End Sub

Integer Variables Example 3-2

Step 3: Now let us use the GoSub statement and perform the addition operation as follows.

Code:

Sub Example3()

Dim i As Integer, b As Integer
i = InputBox("Enter first number")
b = InputBox("Enter second number")
GoSub Addition
MsgBox "Execution Complete"
Exit Sub
Addition:
MsgBox i + b

End Sub

Addition Operation Example 3-3

Step 4: Now we can use the return statement to go back and inform that execution is complete.

Code:

Sub Example3()

Dim i As Integer, b As Integer
i = InputBox("Enter first number")
b = InputBox("Enter second number")
GoSub Addition
MsgBox "Execution Complete"
Exit Sub
Addition:
MsgBox i + b
Return

End Sub

Return Statement Example 3-4

Step 5: Run this code by hitting F5 or Run button placed at the uppermost ribbon of Visual Basic Editor.

VBA Return Example Output 3

Example #4 – VBA Return Statement

For this example look at the below example of code as follows.

Code:

Sub Example4()
Dim i As Integer, k As Integer, area1 As Integer
i = 2
k = 3
area1 = area(i, k)
MsgBox area1
End Sub
Public Function area(x As Integer, y As Integer) As Integer
area = x * y
End Function

VBA Return Example 4-1

In this code, there is no return statement used but it still returns the function with a value.

Explanation of VBA Return

  • We have seen why we use the return statement,  in both of the cases with the use of GoSub statement and User-defined functions. However, there is a slight difference. In the GoSub function, we used a Return statement so that the compiler can return to the next code after the subroutine, and in user-defined functions return statement returned the value to be generated by the function.
  • We have seen two different methods of using the Return statement through the examples above.

Method 1: The first method is the use of GoSub statement with the return statement.

Method 2: The second method is to use return values in a user-defined function.

Things to Remember

There are few things that we need to remember about the Return statement in VBA and they are as follows:

  • The return statement is placed where the execution of codes for the procedures is completed.
  • For the GoSub statement, the GoSub and return statement should be in the same procedure.
  • For User-defined functions, the values are returned using the function name.
  • There can be more than one return statement in the same procedure.

Recommended Articles

This is a guide to the VBA Return. Here we discuss how to Use Go Sub Return Statement in Excel VBA along with practical examples and a downloadable excel template. You can also go through our other suggested articles –

  1. VBA SendKeys (Examples with Excel Template)
  2. How to Change Name Worksheet in Excel VBA?
  3. VBA On Error Goto (Examples)
  4. VBA Input | Excel Templates

Excel VBA Return Statement

VBA is wonderful and a lifesaver for those who know the in and out of VBA codingVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more. It can save tons of time at our workplace. In our earlier articles, we discussed many things and concepts of VBA return. One such concept is the GoSub Return statement. In this article, we will introduce you to these concepts.

Table of contents
  • Excel VBA Return Statement
    • What is GoSub Return Statement?
    • How to use GoSub Return Statement in VBA?
      • Example #1
      • Example #2
    • Things to Remember
    • Recommended Articles

VBA-Return

What is a GoSub Return Statement?

The statement “GoSub” means it will go to the line of code indicated by label through name and performs a specific set of the task until it finds the statement “Return.”

It is similar to the error handler statement “GoTo Label,” but what “GoSub Return” does is return to the next line of code rather than continuing from the label name.

Below is the syntax of the VBA GoSub Return statement.

GoSub [Label Name]
….. Line of Code
[Label Name]:
….. Line of Code to perform the task

We know it is not easy to understand from reading the syntax but using the example, you may be able to understand the concept.

Before we become go-to examples, let me tell you a few things about this statement.

  • The GoSub statement calls a subroutine in VBASUB in VBA is a procedure which contains all the code which automatically gives the statement of end sub and the middle portion is used for coding. Sub statement can be both public and private and the name of the subprocedure is mandatory in VBA.read more, named by a label within the same routine or Function.
  • Both GoSub and Return should be within the same procedure. This is because we cannot call another subroutine macro here.
  • You can introduce any number of GoSub Return statements.
  • A return statement will continue the execution of the code from where it left off before it jumps to the sub procedure indicated by a label name.

How to use GoSub Return Statement in VBA?

You can download this VBA Return Excel Template here – VBA Return Excel Template

Example #1

To understand the usage of this statement, look at the below code first. Later, we will explain to you the code line by line.

Code:

Sub Go_Sub_Return()

  GoSub Macro1 'Label Name1
  GoSub Macro2 'Label Name2
  GoSub Macro3 'Label Name3

  Exit Sub

Macro1:
  MsgBox "Now running Macro1"
Return

Macro2:
  MsgBox "Now running Macro2"
Return

Macro3:
  MsgBox "Now running Macro3"
Return

End Sub

Let us run the code by pressing the F8 key to understanding this code. After pressing the F8 key first, it will initiate the macro running.

VBA Return Example 1

Now, press the F8 key once more to go to the next line.

VBA Return Example 1-1

We all know Macro will run the code line by line. But if you press the F8 key, it will not go to the next line. Rather, it works differently.

VBA Return Example 1-2

It has jumped to the label named “Macro1” this is because in the previous statement “GoSub,” we have instructed the Macro to go to the subprocedure label name “Macro1”, so accordingly, it has jumped to the respective label name.

By pressing the F8 key, excel macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
read more
will execute the label “Macro1” task of showing the result in the message box.

VBA Return Example 1-3

Click on the “OK” message to return to the coding window.

VBA Return Example 1-4

Now, it has highlighted the “Return” statement. So, if you press the F8 key one more time, what it will do is it will “Return Back” to the previous line of code before it jumps to the label name.

VBA Return Example 1-5

The last time it executed the code “GoSub Macro1,” it performed the label name “Macro1” task. Since we have mentioned the “Return” statement, it is back to the next line of code i.e.

“GoSub Macro2”

What the statement says is, “go-to label named Macro2”. In the below label “Macro2”, we have mentioned a specific set of tasks.

VBA Return Example 1-6

Now, we will get the second subprocedure task of showing value in the message box.

VBA Return Example 1-7

Now, click on “OK.” It will highlight the second “Return” statement.

VBA Return Example 1-8

Upon clicking the F8 key, it will return to the next line of code before returning to the label “Macro2”. Now, it will highlight “GoSub Macro3.”

VBA Return Example 1-9

Now, it will go to the label “Macro3” and press the F8 key.

Example 1-10

Now, it will execute the third label task.

Example 1-11

Now, click on “OK.” It will highlight the “Return” statement.

Example 1-12

Now, press the F8 key again. It will jump back to the line of code “Exit Sub.”

Example 1-13

No, it will exit the subroutine. Therefore, it is necessary to add the word “Exit Sub.” Otherwise, it will encounter an error.

Example #2

Now, look at one more example of using the GoSub Return statement.

Code:

Sub Go_Sub_Return1()

  Dim Num As Long

  Num = Application.InputBox
  (Prompt:="Please enter the number here", Title:="Divsion Number")

  If Num > 10 Then
  GoSub Division
  Else
    MsgBox "Number is less than 10"
    Exit Sub
  End If
  Exit Sub

Division:
  MsgBox Num / 5
Return

End Sub

This code will ask you to enter the number which is >10. If the number is >10, then it will perform the task of dividing it by 5 (Label Name is “Division”), or else it will show the message as “Number is less than 10.

VBA Return Example 2

Things to Remember

  • The label name should be the same in the GoSub and Return statement, and in the return statement label name should be followed by a colon (:).
  • We must always use Exit Sub in VBA after making all the return statements to avoid the error message.

Recommended Articles

This article has been a guide to VBA Return. Here, we learn how to use GoSub Return Statement in VBA, examples, and a downloadable Excel template. Below are some useful Excel articles related to VBA: –

  • VBA IsDate
  • VBA VARTYPE Examples
  • Switch in VBA
  • Filter in VBA

Понравилась статья? Поделить с друзьями:
  • How to pronounce the hardest word
  • How to restore excel file
  • How to pronounce any word in english
  • How to report from excel
  • How to pronounce any word correctly