Trending February 2024 # How To Use Excel Vba Goto Statement? # Suggested March 2024 # Top 5 Popular

You are reading the article How To Use Excel Vba Goto Statement? updated in February 2024 on the website Achiashop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 How To Use Excel Vba Goto Statement?

Excel VBA GoTo Statement

VBA Goto Statement is used for overcoming the predicted errors while we add and create a huge code of lines in VBA. This function in VBA allows us to go with the complete code as per our prediction or assumptions. With the help Goto we can go to any specified code of line or location in VBA. There is two way of doing it which we will see in upcoming examples.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

How to Use Excel VBA Goto Statement?

We will learn how to use Excel VBA Goto Statement with a few examples.

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

Example #1

The first way of using VBA Goto is by Application.Goto method. With the help of Application.Goto statement we can to any specific location, workbook or worksheet which is opened currently. This statement will look like as below.

[Reference]: This is nothing but a specified cell reference. If the reference is not provided by default it will take you to the last used cell range.

[Scroll]: This a logical statement of TRUE or FALSE. If the value is TRUE it will scroll through the window, if the value if FALSE it will not scroll through the window.

Now it will open a new Module. There write the Subcategory of a macro with the name of Goto as we are performing that code as shown below.

Code:

Sub

VBAGoto()

End Sub

Now write Application.Goto to enable to application or place where we want to go.

Code:

Sub

VBAGoto() Application.Goto

End Sub

After that give Reference to any worksheet or workbook and range of cells. Here we have given the range of Cell B3 and Worksheets of named as “VBA Goto”.

Code:

Sub

VBAGoto() Application.Goto Reference:=Worksheets("VBA_Goto1").Range("B3"),

End Sub

Now for actually going to the mentioned cell we need to add Scroll argument which will directly take us to the specified cell. Now we will change the scroll argument from FALSE as shown below.

Code:

Sub

VBAGoto() Application.Goto Reference:=Worksheets("VBA_Goto1").Range("B3"), Scroll:=

False

End Sub

After running the code using F5 key or manually, we will see cursor will get shifted to cell B3 without changing the orientation of the selected sheet as shown below.

Now we will change Scroll argument from FALSE to TRUE.

Code:

Sub

VBAGoto() Application.Goto Reference:=Worksheets("VBA_Goto1").Range("B3"), Scroll:=

True

End Sub

Example #2

There is another way of using VBA Goto argument. Using Goto in VBA by this example, we can skip the argument which is causing an error. For this, insert a new module in VBA and start Subcategory with the name of argument used as shown below. You can use any other name.

Code:

Sub

VBAGoto()

End Sub

For this, we will consider 3 integers X, Y, and Z by opening Sub category in VBA as shown below.

Code:

Sub

VBAGoto()

Dim

X

As Integer

, Y

As Integer

, Z

As Integer

End Sub

Now also consider some mathematical division where we will divide 10, 20 and 30 with 0, 2 and 4 as shown below.

Code:

Sub

VBAGoto()

Dim

X

As Integer

, Y

As Integer

, Z

As Integer

X = 10 / 0 Y = 20 / 2 Z = 30 / 4

End Sub

If we run the code we will get the same error message of Run-time error 11.

Above error message Run-time error ‘11’ comes only when the written mathematical expression is incorrect. Now to overrule this error, we will use text On Error GoTo with word YResult to skip error message and get the output which works fine as shown below.

Still, our code is not complete. Using Goto with statement “YResult:” will only skip the error line of code. But it will again show the error as Labe not defined as shown below.

Code:

Sub

VBAGoto()

Dim

X

As Integer

, Y

As Integer

, Z

As Integer

On Error GoTo

YResult: X = 10 / 0 Y = 20 / 2 Z = 30 / 4

End Sub

Now to complete it, we need to define the Label. Label is the part of statement in VBA Coding, which is used when we want to skip a certain portion of code to any defined applicable line of code. As we already have YResult with Goto argument. Then we will insert the same just before integer Y. Now run the code again.

Code:

Sub

VBAGoto()

Dim

X

As Integer

, Y

As Integer

, Z

As Integer

On Error GoTo

YResult: X = 10 / 0 YResult: Y = 20 / 2 Z = 30 / 4

End Sub

As seen and done, we have not got any error message which means that our code is correct and it is skipping that line of code which was causing an error and giving the output where the correct code has been written. Now to print the result of code need to insert message boxes for each Integer with the help argument MsgBox as shown below.

Code:

Sub

VBAGoto()

Dim

X

As Integer

, Y

As Integer

, Z

As Integer

On Error GoTo

YResult: X = 10 / 0 YResult: Y = 20 / 2 Z = 30 / 4 MsgBox X MsgBox Y MsgBox Z

End Sub

Once done then run the complete code to see the output. We will the output of division of each defined integers as 0, 10 and 8 as shown in below screenshot as well.

On Error GoTo YResult statement helped us to directly jump to mentioned result point integer as we did for integer Y. And the output for X as 0 shows that there was incorrect statement argument written. We can the Label even before Z but that would give us the result of Z integer only. For X and Y it will again show 0 as output.

Pros of VBA On Error

We can calculate any mathematical formula even if it is incorrect.

For bigger coding structures where there are chances or having an error, using GoTo may give correct result even among the line of codes.

This gives better result as compared to the result obtained from normal excel calculations in spite of having an incorrect argument.

Things To Remember

Remember to the file in Macro-Enabled Excel file so that we can use created VBA code many and multiple times.

Compile the written code before implementing with any excel requirement.

Use Label as shown in example-2 appropriately so that we will get the result for the complete correct code.

Recommended Articles

This has been a guide to VBA GoTo Statement. Here we discussed how to use Excel VBA GoTo Statement along with some practical examples and downloadable excel template. You can also go through our other suggested articles –

You're reading How To Use Excel Vba Goto Statement?

How To Record Macro In Vba With Excel Examples

Introduction to Excel VBA Macros

If you are a frequent Microsoft Excel user, you must have done some routine work, like inserting cells in excel, formatting the cells every time, inserting rows or columns, inserting numbers as per our requirements, etc. These tasks might consume a lot of your time on a day-to-day basis. Is there any way to reduce the time these tasks take every now and then? In short, is there any way to automate these tasks so that you don’t need to work on them every now and then? The answer is a big YES! It is absolutely possible to automate such tasks under Microsoft Excel with the help of Macros.

What is Macro?

Excel is a tool that has been developed and enhanced by the community so that it can be really very handy as well as simple to use. Macro is a small piece of programming code, the same as we have in traditional programming languages such as C, C++, C#, etc. which can be used in excel to automate some of the tasks. In Excel, we have a separate environment to work on Macros. It is called Visual Basics for Applications. Within this environment, you can write, store as well as run the piece of codes using which you can automate the day-to-day stuff.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

How to Enable Developer’s Tab?

Before being able to create, store and run a macro, you need to first enable Developer’s Tab. This tab contains several options associated with Macros such as recording a macro, stop recording a macro, etc. We will see step by step how to enable the developer’s tab in Excel to proceed further with creating a macro.

Step 1: Go to the File menu tab in the currently open Excel sheet.

As soon as you hit OK, you can see the Developer tab active in the Excel ribbon menu with a bunch of different options available under. See the screenshot below.

How to Record a VBA Macro?

Being a VBA automation expert, it all starts with recording a macro.

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

We will now record a simple macro, a one in which you can input your name and navigate to the next cell all automatically. Pretty exciting, isn’t it? Follow the steps below.

Step 1: Navigate towards the Developer tab in your current working sheet which you just enabled.

You can see the whole bunch of options available under the Developer tab. As similarly as a real-life developer or automation expert has several automating options with him.

Step 2: Choose an option called Record Macro. It allows you to record whatever tasks you do on an active excel sheet and create a macro in the backend for the same so that you can automate the stuff.

After you hit OK, your system starts to record the macro. Means, whatever tasks you are going to do in the excel sheet are being stored as a macro. You can see the Record Macro button has changed to Stop Recording. It means that the macro has started to record.

You can see the code under the Module section in Visual Basic Editor pane.

Now we will check whether the macro we have created is working fine or not.

You can see that the name “Lalit Salunkhe” is inputted in cell A2 and cell A3 is selected next.

This is how we can record a macro in excel. Don’t forget to save this file as a Macro enabled file so that all the macro’s get stored in the VBE.

Creating Squared Numbers using Macro

Follow the below steps to create squared numbers using macros in Excel VBA.

Step 3: In cell B2, use the asterisk to multiply cell A2 by itself and hence creating a formula same as of squaring a number.

Step 4: Drag the fields down until B11.

Now, in order to test whether the code is working fine or not, delete all the data across columns A and B.

You can see the Numbers and Squares columns will get created respectively along with their column headers.

This is how we can record and use a macro.

Things to Remember About VBA Macros

Always make sure you save the file as an Excel Macro-Enabled sheet so that the macro gets recorded in and can be used.

It is always a good practice to record a macro as it can be used for further automation irrespective of the workbooks.

Recommended Articles

This is a guide to VBA Macros. Here we discuss how to record macros in Excel and how to create a squared number using macros along with practical examples and downloadable excel template. You may also look at the following articles to learn more –

Examples Of Excel Vba Dateadd Function

Excel VBA DateAdd

VBA DateAdd is a function which performs addition or subtraction of time/date intervals. This will return date by adding or subtracting a specified time interval. It is quite difficult to deal with date and time when you do some calculations on it. But in our daily work, it is an essential type of data that we may use. Comparison, addition, subtraction between different dates are some familiar operations that we do.

Formula For DateAdd function in Excel VBA

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

The formula for VBA DateAdd function is very simple in format.

Let’s see what are the parameters used in the Excel VBA DateAdd function.

Interval: This can be a time/date interval that you want to add or subtract. This represents what kind of value you wish to add or subtract. This can be a component of date or time like days, month, etc. The scope of intervals is given below.

Number: Is the number of intervals you want to add. Use a positive number to add the interval with the given date and negative value to subtract the interval from the date.

Date: The date to which you want to add/subtract the interval. Operations will be performed on this date and return date as output.

Examples of Excel VBA DateAdd Function

Below are the different examples of DateAdd Function in Excel VBA:

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

Example #1 – Add Date

Let’s see how to add a particular number with the given date using VBA DateAdd Function.

We need to find the date after adding ’10’ days with the date ‘25/10/2024’

Start sub procedure with a name. Here we created a sub procedure named ‘adddate’.

Code:

Sub

adddate()

End Sub

Create a variable as date datatype, variable name is currentdate.

Code:

Sub

adddate()

Dim

currentdate

As Date

End Sub

We are going to store the result in this variable currentdate.

We want to add ‘10’ days with ‘25/10/2024’. So the number of days want to add is 10. And the interval is ‘d’ and the number is 10.

So let’s apply the VBA DateAdd function as below.

Code:

Sub

adddate()

Dim

currentdate

As Date

currentdate = DateAdd("d", 10, "25/10/2024")

End Sub

After applying the formula to the variable let’s use a message box to print the result.

Code:

Sub

adddate()

Dim

currentdate

As Date

currentdate = DateAdd("d", 10, "25/10/2024") MsgBox Format(currentdate, "dd-mm-yyyy")

End Sub

Run the code by pressing F5. The result will be shown as

You can see the result as shown above.

Example #2 – Add Months

To add months with the given date the interval needs to change as “m”.

Add ‘2’ with the date “15/2/2024”. The code can be written as below.

Code:

Sub

addmonth()

Dim

currentdate

As Date

currentdate = DateAdd("m", 2, "15/2/2024") MsgBox Format(currentdate, "dd-mm-yyyy")

End Sub

The output date will be changed as below.

Example #3 – Add Year

To add years with the given date the below code can be used.

The interval should be” yyyy”

Add 4 years with’20/2/2024’

Code:

Sub

addyear()

Dim

currentdate

As Date

currentdate = DateAdd("yyyy", 4, "20/2/2024") MsgBox Format(currentdate, "dd-mm-yyyy")

End Sub

The result will be as below. The variable currentdate will return ‘20/2/2024’

Example #4 – Add Quarter

While adding quarter, three months will be added to the date since the quarter if 12 months is 3.

The interval should be mention as “Q”, the number given in the formula specifies how many quarters should be added. For example, DateAdd(“Q”,2, ”22/5/2024”) number of quarters is 2 so 6 months will be added.

To add 2 quarters with ‘22/5/2024’ below code can be used.

Code:

Sub

addquarter()

Dim

currentdate

As Date

currentdate = DateAdd("Q", 2, "22/5/2024") MsgBox Format(currentdate, "dd-mm-yyyy")

End Sub

The result will be as below.

Example #5 – Add Seconds

You can add time along with date displayed. To get this mention the interval as “s” which indicates seconds.

To display five seconds with date ‘28/3/2024’ can use the below formula.

Code:

Sub

addseconds()

Dim

currentdate

As Date

currentdate = DateAdd("s", 5, "28/3/2024") MsgBox Format(currentdate, "dd-mm-yyyy hh:mm:ss")

End Sub

While showing the output with date seconds will be displayed.

Example #6 – Add Weeks

To add a number of weeks with the given date, use the interval as “WW”

Code to find the date after the given number of weeks from’27/03/2024’

Code:

Sub

addweek()

Dim

currentdate

As Date

currentdate = DateAdd("WW", 2, "27/3/2024") MsgBox Format(currentdate, "dd-mm-yyyy")

End Sub

The output will be the date after 2 weeks.

Example #7 – Add Hours

To get a particular time with a date this is used.

In interval mention the “h” and also change the format of the output.

The code to get the hours printed with a date is.

Code:

Sub

addhour()

Dim

currentdate

As Date

currentdate = DateAdd("h", 12, "27/3/2024") MsgBox Format(currentdate, "dd-mm-yyyy hh:mm:ss")

End Sub

The result will be shown with time in hh:mm:ss.

Example #8 – How to Subtract Weeks using VBA DateAdd Function?

Similar to addition, subtraction can also perform using VBA DateAdd function. The numbers specified as positive integers along with the formula. To perform subtraction, use these numbers as negative integers. For example, change the formula as below.

DateAdd (interval, - number, date)

By using the above method will try to find the day subtracting three weeks from ‘28/3/2024’

Create a subprocedure as subdate.

Code:

Sub

subdate()

End Sub

Define a variable to store the result. Currentdate is a variable as date type to assign the final result.

Code:

Sub

subdate()

Dim

currentdate

As Date

End Sub

To subtract three weeks from ‘28/3/2024’ will apply the formula. DateAdd(“ww”, -3, “28/3/2024”)

Code:

Sub

subdate()

Dim

currentdate

As Date

currentdate = DateAdd("ww", -3, "28/3/2024")

End Sub

‘-3’ indicates the subtraction “ww” is the interval since we want to operate on weeks.

The formula is applied and the result is stored in currentdate.

Code:

Sub

subdate()

Dim

currentdate

As Date

currentdate = DateAdd("ww", -3, "28/3/2024") MsgBox Format(currentdate, "dd-mm-yyyy")

End Sub

The result after subtracting three weeks from the given date is displayed below.

Things to Remember

The interval and date mentioned in the formula will be given within a double quotation.

If you use weekdays interval” w” it will work similarly to the interval day “d” since the weekday calculates 1=Sunday, 2=Monday, etc. in So it will count the holidays even you use weekdays.

The out will be displayed according to the date format settings on your system. Use format along with a message box to print the result in the format you want.

Within the VBA DateAdd function use the number as negative to perform subtraction among dates.

Recommended Articles

This is a guide to Excel VBA DateAdd Function. Here we discuss the examples of VBA DateAdd function to add & subtract days, months & years from the given date along with practical examples and downloadable excel template. You can also go through our other suggested articles –

How To Use The Count Functions In Microsoft Excel

How to Use the COUNT Function

The COUNT function in Excel is one of the most basic of the five functions. Use it to count the number of cells containing values, which is handy for seeing the number of sales, reviews, or numeric grades in your sheet. Note that text is not counted as a value.

The syntax for the formula is COUNT(value1, value2,…), where only the first argument is required. You can enter the range of cells and add up to 255 additional items or cell ranges using the remaining arguments.

For this first example, we’re using the COUNT function via the following formula to total the number of cells containing values in our range B2 through B11:

=

COUNT

(

B2

:

B11

)

To show the difference if you have text in a cell rather than a number, you can see our next result is 9 instead of 10, as cell B8 contains the word “six.”

If you want to count the total numbers in a cell range, but not place the formula in your sheet, use the Status Bar at the bottom of the Excel window.

How to Use the COUNTA Function

The syntax is similar to the COUNT function, COUNTA(value1, value2,…), where only the first argument is required, and you can include up to 255 additional arguments. Keep in mind that the function counts cells that contain errors, formulas, and formula results, as these cells are not blank.

In this example, we’re using the following formula to count the number of cells containing values in our range B2 through C11:

=

COUNTA

(

B2

:

C11

)

Our result is 16, as that’s the number of cells in our range that contain values.

Note: if you need to remove empty cells or want to surface data that meets specific criteria, try using filters in Excel.

How to Use the COUNTBLANK Function

The syntax is COUNTBLANK(range), where you have just one argument for the cell range.

Using the following formula, we’re counting the number of blank cells in the range B2 through C11:

=

COUNTBLANK

(

B2

:

C11

)

Our result is 4 empty cells.

Tip: want to reorganize your data so that columns become rows and vice versa? Transpose your data in Excel to make that happen.

How to Use the COUNTIF Function

The syntax is COUNTIF(value, criteria), where both arguments are required. Use the “value” argument for the cell range and the “criteria” argument for the data you want to locate. You’ll need to place the condition you use for the second argument within quotation marks if it’s text or a comparison operator.

In this first example, we’re counting the number of cells in the range B2 through B11 that contain the number 10 with this formula:

=

COUNTIF

(

B2

:

B11,

10

)

The result is 3 cells that contain the value of 10.

For an example using text, we’re counting the number of cells in the range A2 through A11 that start with “San.” Use the formula:

=

COUNTIF

(

A2

:

A11,

"San*"

)

“San*” was added in quotation marks using an asterisk (*) as a wildcard so that any letters after “San” are counted. We received a result of 2.

For an example that uses a comparison operator, we’re counting the number of cells in the range C2 through C11 that are less than or equal to 5,000 with this formula:

=

COUNTIF

(

C2

:

C11,

"<=5000"

)

We placed our comparison operator “<=5000” within quotes and received a count of 7.

How to Use the COUNTIFS Function

If you like the idea of entering criteria for the cells you want to count but would like to narrow it down even further or total values in more cells, use the COUNTIFS function. You can count cells that contain multiple conditions instead of just one when using the COUNTIF function.

The syntax is COUNTIFS(range1, criteria1, range2, criteria2,…), where the first two arguments are required for the cell range and condition. Use the additional arguments for the second set of cells and/or conditions.

For this example, we’re counting the number of records containing a 10 in the range B2 through B11 and a value of 1,000 in the range C2 though C11 using this formula:

=

COUNTIFS

(

B2

:

B11,

10

,C2

:

C11,

1000

)

Our result is 2 records that have both 10 and 1,000 in those cell ranges.

Using a text example, we’re counting the number of records that start with the letter “S” in the range A2 through A11 and have a value greater than 9 in the range B2 through B11 with this formula:

In another example, we’re using the same cell range for multiple criteria. We’re counting the number of records that have a value less than 10,000 and greater than 2,000 in the range C2 through C11 with this formula:

Tip: if you also use Google’s apps, check out several helpful functions for Google Sheets, too.

Frequently Asked Questions How do I auto count cells in Excel?

If you need to add numbers to cells in a column or row, use Excel’s auto-fill feature. To start counting at one, enter 1 in the first cell and 2 in the second cell. Then, select both cells and drag the fill handle (square in the bottom-right corner) down a column or across a row to fill the remaining cells.

To use a different numbering scheme, for example, 10, 20, 30, and so on, enter the first two numbers you want to use in the first two cells, then use the fill handle. Excel should recognize your numbering pattern and comply.

How do I sum values in Excel?

You can use the SUM function to add values in cells together. This is handy for totaling your monthly bills, sales, or inventory.

The Status Bar in Excel shows information about your sheet, errors you may encounter, and quick calculations, like those mentioned above. This displays at the bottom of the window in Excel, as well as other Microsoft applications, like Word and PowerPoint.

Image credit: Pixabay. All screenshots by Sandy Writtenhouse.

Sandy Writtenhouse

With her BS in Information Technology, Sandy worked for many years in the IT industry as a Project Manager, Department Manager, and PMO Lead. She wanted to help others learn how technology can enrich business and personal lives and has shared her suggestions and how-tos across thousands of articles.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Sign up for all newsletters.

By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time.

How To Use Ink To Shape In Word, Powerpoint, Excel

Microsoft is known to update its Microsoft Office products with new features frequently. As artificial  intelligence takes over, Microsoft 365 products have grown smarter. Now, you can convert hand sketched shapes into perfect ones. The procedure to use the Ink to Shape feature in Microsoft Office has been explained in this article.

How to use Ink to Shape in Word

The Ink to Shape feature works with Microsoft Word. It is very useful when images are inserted from external sources. The procedure is as follows:

Assume the images are already present in your Microsoft Word document.

Now, go to the Draw tab.

Now, use the Lasso select tool to select the shapes you wish to convert. The tool is the second option on the list.

See the magic as the shapes convert to perfect shapes!

How to use Ink to Shape in PowerPoint

Just like Microsoft Word, the Ink to Shape feature can be used with Microsoft PowerPoint. The procedure is pretty much the same as with Word.

Go to the Draw tab.

Use the Lasso select tool to select the shapes you wish to convert. The tool is the second option on the list.

How to use Ink to Shape in Excel

Unlike with Microsoft Word and PowerPoint, Microsoft Excel does not have the Draw tab by default. So, the procedure to use the Ink to Shape feature in Microsoft Excel is as follows:

Go to the Customize Ribbon tab.

In the list of Main tabs, check the box associated with Draw.

Now, the Draw tab will appear.

Go to the Draw tab.

Use the Lasso select tool to select the shapes you wish to convert. The tool is the second option on the list.

Similarly, you can create Shapes in OneNote using Ink to Shape feature.

Why can I not just add the shapes?

Microsoft Office products do have an option to insert shapes using the Insert tab. However, if you have an image with multiple shapes, it will be very cumbersome to create perfect shapes of the exact size and dimensions. In this case, the Ink to Shape feature comes out to be very helpful.

Can I select few shapes and not all full conversion?

You can use the combination of the Lasso select tool and the Ink to Shape feature multiple times to make sure that you do not select all shapes but only the ones which you look forward to converting. Rather this is the reason the Ink to Shape feature was created at the first place.

How to draw shapes in Microsoft Office?

You can draw shapes in Microsoft Office using the Draw feature. There are various pens and brushes available to draw the shape of your choice. You can also change the color of the drawn shapes. Furthermore, You can also use the Highlighter in the drawings.

How to convert drawn text into type text?

Just like the Ink to Shape feature, we have the Ink to Text feature with Microsoft Office products. You can use this feature to select the hand-drawn text and convert it to type text. After the conversion, you can change the size and font of the text as well.

How to add typical shapes in Microsoft Word, Excel, and PowerPoint? How to check the size of the shapes you created?

You can easily check the size of the shapes you created using the Ruler option. The Ruler can also be rotated and slid. It can be used to check the dimensions of all basic shapes. Other than this, when you create shapes using the Insert option, the size can be chosen.

Learn The Use Cases For Return Statement

Introduction to MATLAB Return

In computer programming, a return statement is defined to be executed to return the control to the parent sub routine from the invoking subroutine. The flow of execution resumes at the point in the program code immediately after the instruction, which is called its return address, and the running scope of the code can be defined as the called subroutine. In the absence of a parent subroutine, the return statement returns the control of execution to the command prompt. In this topic, we are going to learn about Matlab return.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax

The return command redirects the control to invoking script or function instead of letting MATLAB execute the rest of the consecutive commands in the called subroutine. MATLAB redirects the control nothing but to the command prompt when a script or a function contains a return, and it is not being called from any invoking program.

Use cases for a return statement

Return command is used in different conditions based on the technical requirement of the program. It can also be used for data validity checking functionality. Some of the important use cases are discussed below.

1. Bringing control to keyboard

If a program needs the user to take action on the occurrence of some specific condition, the current subroutine or function can be called directly without being triggered by any parent sub routine, and the flow of control returns to the command prompt or the keyboard when the command ‘return’ is executed.

Example:

The below code snippet defines a function findindex() where the return command is used with 2 purposes:

Performing validation checking on input data

Returning control to keyboard once the match is found

endfunction

Case 1: The return statement is executed on a negative input being given

findindex(-15,[12 34 54 15 32])

Output:

Case 2: The return statement is executed on match to the input data is found

findindex(15,[12 34 54 15 32])

Output:

2. Redirecting execution flow to the parent (calling) subroutine from the called subroutine

If the program needs to reroute the flow of control to the calling subroutine or the calling function on the occurrence of some specific condition. It can be carried out when its parent subroutine triggers the current in the current subroutine or function, and the command ‘return’ is executed.

Example:

The below code snippet defines a function findindex() within another function callfunction() where the return command is used with 2 purposes:

Performing validation checking on input data of findindex() function

Returning control to callfunction() from findfunction() return command

function resultfunc = callfunction(inputval,referenceArray)result=findindex(inputval,referenceArray); if isnan(result)disp(‘Match is not found.’)    elsedisp([‘Match is found at ‘ num2str(result)])    endendfunction

callfunction(-12, [10 21 14 15 20 12 20])

Case 2: The return statement is executed on match to the input data is found

callfunction(12, [10 21 14 15 20 12 20])

Output:

3. Usage of return and continue statement in a loop

The program can have the flexibility to decide on which condition the flow of control should be rerouted to its calling sub routine or the command prompt and on which condition will force the flow to stay in the current system.

Example:

The below code snippet defines a function findindex() within another function callfunction() where the return command is used with 2 purposes:

Performing validation checking on input data of findindex() function

Returning control to callfunction() from findfunction() return command when the match is found and make the flow stay within the loop using the command ‘continue’ when the matched element is not found.

Example:

endfunction

findindex(-15,[12 34 54 15 32])

 Output:

Case 2: The return and continue statement execution based on finding matched or non-matched element

findindex(15,[12 34 54 15 32])

Output:

Advantages of Matlab return

Using a return statement prevents the execution of unwanted functionalities once the desired condition is satisfied. As a result, it improves code quality and optimizes the code execution. As it reduces the number of instructions to be executed, it also reduces the execution time for the program. Thus it

makes the execution faster and results in improving the performance. Use of return statement in association with ‘continues’ statement provides flexibility to the program to decide whether to reroute the flow of control or keep it running within the current scope of the code.

Additional note

While using return within conditional blocks, such as if or switch, or within loop control statements, such as, for or while, the programmer needs to be careful. In MATLAB, when the control flow reaches a return statement in a conditional block, it just exits the loop and exits the script or function in which the return command is executed. Hence directly, it returns control to the invoking subroutine or commands prompt.

In MATLAB, it is not supported to return values using the return statement. To send a return value, it is required to set the value of each ‘out’ arg. Functions may return more than one argument as return values.

Recommended Articles

This is a guide to Matlab return. Here we discuss the Use cases for the return statement along with the examples, cases and outputs. You may also have a look at the following articles to learn more –

Update the detailed information about How To Use Excel Vba Goto Statement? on the Achiashop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!