Excel vba sub return

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

Return to VBA Code Examples

In this Article

  • Using Variables to Return a Value
    • Global Variable
  • Using a Sub Procedure to Populate an Excel Sheet

This tutorial will demonstrate how to return a value from a sub procedure in VBA.

A sub procedure is not designed to return a value – that is what a function procedure is used for. However, there may be a time where you are running some code in a sub procedure where you need to get a value from that sub procedure. The way to do this is to use Module or Global Variables or to use a Sub Procedure to populate an Excel sheet.

Using Variables to Return a Value

You can declare variables at the module-level. When doing so, those variables can be used anywhere within the module and the variables retain their values. To declare a variable at the module-level, simply declare the variable at the top of your code module:

Option Explicit
Dim dblQty as Double

Sub TestA()
'call the TestB sub
   Call TestB
'show the variable value in the module window
   Debug.Print dblQty
End Sub
Sub TestB()
'populate the module variable
   dblQty = 900
End Sub

To put these together, we run TestA, which in turn would call TestB and give us the value of 900 in the immediate window.

vba sub module variable

This only works within the module, as the variable has been declared using the Dim statement at Module level.

Global Variable

You can declare the variable at a global level to use it throughout your project modules.

vba sub global variable

Using a Sub Procedure to Populate an Excel Sheet

Another way to reference values calculated from a Sub Procedure, is to simply write the data to an Excel Sheet and then reference that data in another procedure.

Sub PopulateRange()
   Range("A1") = "Product"
   Range("B1") = "Quantity"
   Range("C1") = "Cost"
End Sub

You can then reference those values in another procedure by referencing the cell values:

Sub RetrieveRange()
   Dim Product as String, Quant as long, Cost as double   

   Product = Range("A1")
   Quant = Range("B1")
   Cost = Range("C1")
End Sub

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!
vba save as

Learn More!

As You may know, in general in programming to return a result from function there is Return statement. Even Visual Basic has it. Unfortunately there is no such thing in VBA. In this article I’m going to show You how to return a result from VBA function.

Let’s start with function

For the purpose of this article I’ve created functionModulo, which is very similar to the Mod function.

Function functionModulo(x As Integer, y As Integer) As Boolean

Dim divisionRest As Double, divisionRestStatus As Integer
Let divisionRest = x / y - Fix(x / y)

If divisionRest > 0 Then
    divisionRestStatus = 0
Else
    divisionRestStatus = 1
End If

If divisionRestStatus = 1 Then
    functionModulo = True
Else
    functionModulo = False
End If

End Function

This function allows You to check if there is a divisibility between two numbers. If there is a rest from division the function returns False, if there is no any – function returns True.

So to describe the work of this function, I was using return word. But not as a statement in code. To return the result in VBA function You need to use the function name itself and put it a value.

functionModulo = True

Unfortunately the function not stops there and exits. It just go further.

As close as possible

I decided to modify this function to make it as similar to Return statement schema as possible.

So first of all I cut it a little bit.

Function functionModulo(x As Integer, y As Integer) As Boolean

Dim divisionRest As Double
Let divisionRest = x / y - Fix(x / y)

If divisionRest > 0 Then
    functionModulo = False
Else
    functionModulo = True
End If

End Function

Then I wanted to have the same effect after returning the result from function as Return statement brings.

Function functionModulo(x As Integer, y As Integer) As Boolean

Dim divisionRest As Double
Let divisionRest = x / y - Fix(x / y)

If divisionRest > 0 Then functionModulo = False: Exit Function
If divisionRest = 0 Then functionModulo = True

End Function

That’s why after returning the value I added Exit Function.

If divisionRest > 0 Then functionModulo = False: Exit Function

I was almost done, but also figured out that we can only check for valid values. This means that I could set False value at the beginning as default. One conditional less in code. Cleaner the code.

Function functionModulo(x As Integer, y As Integer) As Boolean

functionModulo = False

Dim divisionRest As Double: Let divisionRest = x / y - Fix(x / y)

If divisionRest = 0 Then functionModulo = True

End Function

Having nothing after the conditional for True value I decided to erase Exit Function statement. In this case it is not needed, but in general it is really good approach to simulate Return statement as from other programming languages.

To sum up

To avoid unnecessary conditionals put the default value at the beginning of the function. You can also do that in the end of the code, only if You simulate the Return statement in VBA – pass the result in the function name and Exit Function just right after that line.

I’m very advanced in VBA, Excel, also easily linking VBA with other Office applications (e.g. PowerPoint) and external applications (e.g. SAP). I take part also in RPA processes (WebQuery, DataCache, IBM Access Client Solutions) where I can also use my SQL basic skillset. I’m trying now to widen my knowledge into TypeScript/JavaScript direction.
View all posts by Tomasz Płociński

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

Содержание

  1. Excel VBA Function Tutorial: Return, Call, Examples
  2. What is a Function?
  3. VBA Syntax for declaring Function
  4. Writing and Using Functions in Excel Visual Basic
  5. How to Write Functions in VBA
  6. Calling Functions from Another Subroutine
  7. Displaying the Value of a Function in the Immediate Window
  8. Calling a Function from Excel
  9. Excel VBA Tutorial – #10 Using built-in Excel functions
  10. #1 – The most often used Excel functions
  11. Variables needed
  12. #2 – SUM
  13. #3 – COUNTIF
  14. Excel VBA Tutorial Part 4 — VBA Function & Sub Procedures
  15. User-Defined VBA Function & Sub Procedures
  16. Arguments
  17. Optional Arguments
  18. Passing Arguments By Value and By Reference
  19. VBA Function Procedures
  20. VBA Function Procedure Example: Perform a Mathematical Operation on 3 Numbers
  21. Calling VBA Function Procedures
  22. Calling a VBA Function Procedure From Within VBA
  23. Calling a VBA Function Procedure From A Worksheet
  24. VBA Sub Procedures
  25. VBA Sub Procedure Example 1: Center and Apply Font Size to a Selected Range of Cells
  26. VBA Sub Procedure Example 2: Center and Apply Bold Font to a Selected Range of Cells
  27. Calling Excel VBA Sub Procedures
  28. Calling a VBA Sub Procedure From Within VBA
  29. Calling a VBA Sub Procedure From A Worksheet
  30. Assigning a Keyboard Shortcut to a Sub Procedure
  31. Scope of VBA Procedures
  32. Early Exit From VBA Function & Sub Procedures

Excel VBA Function Tutorial: Return, Call, Examples

Updated January 20, 2023

What is a Function?

A function is a piece of code that performs a specific task and returns a result. Functions are mostly used to carry out repetitive tasks such as formatting data for output, performing calculations, etc.

Suppose you are developing a program that calculates interest on a loan. You can create a function that accepts the loan amount and the payback period. The function can then use the loan amount and payback period to calculate the interest and return the value.

Why use functions

The advantages of using functions are the same as the ones in the above section on why use subroutines.

Rules of naming functions

The rules for naming functions as the same as the ones in the above section on rules for naming subroutines.

VBA Syntax for declaring Function

HERE in the syntax,

Code Action
  • “Private Function myFunction(…)”
  • Here the keyword “Function” is used to declare a function named “myFunction” and start the body of the function.
  • The keyword ‘Private’ is used to specify the scope of the function
  • “ByVal arg1 As Integer, ByVal arg2 As Integer”
  • It declares two parameters of integer data type named ‘arg1’ and ‘arg2.’
  • myFunction = arg1 + arg2
  • evaluates the expression arg1 + arg2 and assigns the result to the name of the function.
  • “End Function”
  • “End Sub” is used to end the body of the function

Function demonstrated with Example:

Functions are very similar to the subroutine. The major difference between a subroutine and a function is that the function returns a value when it is called. While a subroutine does not return a value, when it is called. Let’s say you want to add two numbers. You can create a function that accepts two numbers and returns the sum of the numbers.

  1. Create the user interface
  2. Add the function
  3. Write code for the command button
  4. Test the code

Step 1) User interface

Add a command button to the worksheet as shown below

Set the following properties of CommanButton1 to the following.

S/N Control Property Value
1 CommandButton1 Name btnAddNumbers
2 Caption Add Numbers Function

Step 2) Function code.

  1. Press Alt + F11 to open the code window
  2. Add the following code

HERE in the code,

Code Action
  • “Private Function addNumbers(…)”
  • It declares a private function “addNumbers” that accepts two integer parameters.
  • “ByVal firstNumber As Integer, ByVal secondNumber As Integer”
  • It declares two parameter variables firstNumber and secondNumber
  • “addNumbers = firstNumber + secondNumber”
  • It adds the firstNumber and secondNumber values and assigns the sum to addNumbers.

Step 3) Write Code that calls the function

  1. Right click on btnAddNumbers_Click command button
  2. Select View Code
  3. Add the following code

HERE in the code,

Code Action
“MsgBox addNumbers(2,3)”
  • It calls the function addNumbers and passes in 2 and 3 as the parameters. The function returns the sum of the two numbers five (5)

Step 4) Run the program, you will get the following results

Источник

Writing and Using Functions in Excel Visual Basic

Most programs you write will begin with the word Sub — but not all:

When you choose Insert —> Procedure. from the VBA code editor menu, you can insert a Sub or a Function (the word Property is discussed in a later blog on classes).

There are two reasons that you might create a function:

  • To help make code easier to write, read and maintain; or
  • To supplement the list of built-in Excel functions.

This blog will show how to do each of these in turn, but first let’s look at the syntax of a function.

How to Write Functions in VBA

The difference between a subroutine and a function in VBA is that a function returns a value. Consider the following very simple function to square a number:

Function Square(AnyNumber As Integer) As Long

‘return the square of any integer

Square = AnyNumber * AnyNumber

There are 3 differences between this and a normal subroutine:

The numbered differences are explained below.

The differences are:

  1. A function begins with Function and ends with End Function (rather than Sub and End Sub).
  2. A function has a data type (this one is of type Long, since we don’t know how big an integer we’ll have to return).
  3. Within a function, you have to set the name of the function equal to something (here, the square of the number contained in the argument).

VB, C# and many other programmers should note that — irritatingly — there is no RETURN statement to return the value of a function in VBA.

You can call functions from Excel (shown in more detail in the final part of this blog), from another subroutine or from the Immediate window. Examples of each follow!

Calling Functions from Another Subroutine

One way to call a function is from another program, or procedure:

The program above (stripped of any error-checking) might read:

Dim n As Integer

‘get the number user wants to square

n = CInt(InputBox(«Type in a number»))

‘show this square

MsgBox «The square of » & n & » is » & _

As you see, you can use Square just as if it were a built-in function in VBA.

Displaying the Value of a Function in the Immediate Window

You can do this in the usual way:

Here we’ve called our Square function 3 times, with a different argument each time.

Again, you can treat your function as if it were one of the built-in ones in VBA.

Calling a Function from Excel

One other way to call a function — and perhaps the sexiest — is to type it into Excel:

The formula for the cell shown above might look like this:

The function takes a single argument, which must be an integer. Here it is the value of cell C2.

One slight annoyance is that when you type the start of a function — in the case above, =Square( — Excel doesn’t suggest possible arguments for it. You can get round this by using the function wizard, as shown in the final part of this blog.

Now that we’ve seen what a function is and how to run one, let’s look at how you might incorporate them into Excel.

Источник

Excel VBA Tutorial – #10 Using built-in Excel functions

Last updated on February 1, 2019 By Victor Chan

Summary: Wouldn’t it be great to run your favorite Excel functions with macros? Like SUM, COUNTIF, VLOOKUP and SUMIF…

In this tutorial, I’ll walk you through code that will allow you to do just that. After we’re finished, you’ll have flexibility you could never achieve with formulas alone!

Difficulty: Intermediate

Download the Sample Workbook

Download the sample file with VBA code

#1 – The most often used Excel functions

If we’re honest, we use only a handful of Excel functions daily. But these functions form the foundation for an Excel power-user.

SUM, SUMIF, VLOOKUP, and COUNTIF are a few of my go-to functions. Without these functions, my office life would be much more difficult. These functions are fast, reliable, and most of my tasks can be completed using only them.

When we use such functions in worksheets, they all require us to input ranges of cells where they will read or write data. More robust functions require even more complex criteria to work properly.

You may wonder why I even mention the inputs required to use basic Excel functions. Since the functions won’t work without the right inputs, when using functions in macros we’ll need to provide the inputs via VBA code.

Also, in our code we’ll need to declare a range type variable to represent each input range. We’ll also need to declare a variable to represent every other required input value for the function(s) we’re using.

Now that we’ve reviewed the basics, let’s start coding!

Variables needed

Considering all the information the functions need, here’s how we’ll declare the necessary variables:

#2 – SUM

I’ll start with the SUM function, as it’s the simplest of the ones we’re going to discuss.

I copied the payroll calculating macro from the previous tutorial. We can use its table to experiment with these Excel functions. As you can see, MaxSalary is 1200, and StateTax is set to 0.2.

Let’s say we want to SUM the salary in column “B”. We will store the result in the “ResultValue” variable.

This is how the code should look:

The third line displays the result in a Msgbox. We could also write the result in a cell – it’s your responsibility, as the programmer, to display the result in the best location.

If you want to put your knowledge to the test, feel free to modify the code as follows:

    Find the last row in column “B” Modify the macro to write the result of the SUM function in the cell below the last row in column “B”

I’m confident you can make these changes with the help of the previous tutorials! Use the power of your knowledge to customize the code the way you want!

#3 – COUNTIF

Using COUNTIF is a bit more complicated, but it’s nothing we can’t solve with VBA!

We’ll use our previously declared variable “rng” for the range. The variable “ResultValue” will again store the result.

This sub will count the occurrences of the number “960” in the dataset. We set “rng” first because the function needs it as input.

We hard-code the searched value (960) in the code. We could’ve used our variable “criteria” instead, but I think it’s more straightforward to show you the code with the hard-coded value.

If you’re performing a COUNTIF on a range of cells formatted as text, you can also add wildcard characters to allow you to count instances of a subset of characters. For example, if you want to count the number of names in column “A” that include the letter “o”, you must put “*” before and after the variable (“search”) that represents the letter “o” in the code.

The code below does just this. As you can see, the code captures the subset of characters for which it’s searching via an InputBox, and it saves that search criteria in the “search” variable.

Источник

Excel VBA Tutorial Part 4 — VBA Function & Sub Procedures

Before you consider creating your own VBA Functions, it is useful to know that there are a large number of built-in VBA functions that you can use in your code.

For a list of the main built-in VBA functions, with examples, see the VBA Functions page.

User-Defined VBA Function & Sub Procedures

In Excel Visual Basic, a set of commands to perform a specific task is placed into a procedure, which can be a Function procedure or a Sub procedure (also known as functions and subroutines).

The main difference between a VBA Function procedure and a Sub procedure is that a Function procedure returns a result, whereas a Sub procedure does not.

Therefore, if you wish to perform a task that returns a result (e.g. summing of a group of numbers), you will generally use a Function procedure, but if you just need a set of actions to be carried out (e.g. formatting a set of cells), you might choose to use a Sub procedure.

Arguments

VBA procedures can be passed data via arguments, which are declared in the procedure definition. For example, you could have a VBA Sub procedure that adds an Integer to every cell in the current selected range on a worksheet. You could supply the value of the integer to the Sub via an argument, as follows:

Sub AddToCells(i As Integer )
.
.
.
End Sub

Note that it is not essential for VBA Functions or Subs to have arguments. Some procedures may not require them.

Optional Arguments

You can also define VBA procedures to have Optional arguments. These are arguments that the user can supply if they want, but if they are omitted, the procedure will assign a default value to them.

To return to the example above, if we wanted to make the supplied integer argument optional, this would be declared as follows:

In this case, the supplied integer, i, has a default value of 0.

You can use multiple Optional arguments in a VBA procedure, as long the Optional arguments are all positioned at the end of the argument list.

Passing Arguments By Value and By Reference

When arguments are passed to VBA procedures, they can be passed in two ways:

  • ByVal — The argument is passed by Value. This means that just the value (i.e. a copy of the argument) is passed to the procedure and therefore, any changes that are made to the argument inside the procedure will be lost when the procedure is exited.
  • ByRef — The argument is passed by Reference. This means that the address of the argument is passed to the procedure. Any changes that are made to the argument inside the procedure will be remembered when the procedure is exited.

You can specify whether an argument is passed to a VBA procedure by value or by reference by using the ByVal or the ByRef keyword when defining the procedure. This is shown below:

Sub AddToCells( ByVal i As Integer )
.
.
.
End Sub
In this case, the integer i is passed by Value. Any changes that are made to i will be lost when you exit the Sub procedure.
Sub AddToCells( ByRef i As Integer )
.
.
.
End Sub
In this case, the integer i is passed by Reference. When you exit the Sub, any changes that have been made to i will be remembered by the variable that was passed into the Sub procedure.

It should be noted that, by default, VBA arguments are passed by Reference. Therefore, if you do not use the ByVal or the ByRef keyword, the arguments will be passed by Reference.

Before discussing further properties of VBA Function and Sub procedures, it is useful to look at the two types of procedure individually. The following two sections provide a brief discussion of VBA Function and VBA Sub procedures, along with simple examples.

VBA Function Procedures

The VBA editor recognises a Function procedure, because the commands are positioned between the following start and end commands:

Function

As previously mentioned, VBA function procedures (unlike sub procedures) return a value. The return values have the following rules:

  • The data type of the returned value must be declared in the Function header.
  • The value to be returned must be assigned to a variable having the same name as the Function. This variable does not need to be declared, as it already exists as a part of the function.

This is illustrated in the following example.

VBA Function Procedure Example: Perform a Mathematical Operation on 3 Numbers

The following code shows an example of a simple VBA Function procedure that receives three arguments, each of which are ‘Doubles’ (double precision floating point numbers). The Function returns a further ‘Double’, which is the sum of the first two arguments, minus the third argument:

The above very simple VBA Function procedure illustrates the way in which data arguments are supplied to a procedure. It is also seen that the Function procedure return type is defined as being a ‘Double’ (i.e. by the term » As Double » which is included after the Function arguments).

The above example also shows how the Function procedure result is stored in a variable that has the same name as the Function.

Calling VBA Function Procedures

If the above simple Function procedure is typed into a Module in the Visual Basic Editor, it will then be available to be called from other VBA procedures or to be used in the worksheets of your Excel workbook.

Calling a VBA Function Procedure From Within VBA

You can call a Function procedure from within your VBA program by simply assigning the Function to a variable. The following example shows a call to the simple SumMinus function that was defined above:

Calling a VBA Function Procedure From A Worksheet

You can call VBA Function procedures from an Excel Worksheet, in the same way as you can call any of the built-in Excel functions.

Therefore, you could call the SumMinus Function procedure by typing the following into any cell of your worksheet:

VBA Sub Procedures

The VBA editor recognises a Sub procedure, because the commands are positioned between the following start and end commands:

VBA Sub Procedure Example 1: Center and Apply Font Size to a Selected Range of Cells

The following code shows an example of a simple VBA Sub procedure that applies formatting to the current selected cell range. The cells are formatted to be aligned centrally (both horizontally and vertically) and to have a user-supplied font size:

The above example illustrates how Sub procedures perform actions but do not return values.

This example also includes the Optional argument, iFontSize. If iFontSize is not supplied to the Sub, then the default font size of 10 is used. However, if iFontSize is supplied to the Sub, then the current range is set to have the user-supplied font size.

VBA Sub Procedure Example 2: Center and Apply Bold Font to a Selected Range of Cells

The following code is similar to example 1, but instead of supplying a font size to the selected range, the cells are set to have a bold font. This example has been included to show a Sub procedure that does not receive any arguments:

Calling Excel VBA Sub Procedures

Calling a VBA Sub Procedure From Within VBA

You can call a VBA Sub procedure from your VBA program by typing the Call keyword, followed by the Sub name and then the Sub procedure arguments enclosed in brackets. This is shown in the example below:

If the Format_Centered_And_Sized Sub procedure had more than one argument, these would be separated by commas. E.g.

Calling a VBA Sub Procedure From A Worksheet

Sub procedures cannot be typed directly into a Worksheet in Excel, in the same way that VBA Function procedures can, because Sub procedures don’t return a value. However, provided they have no arguments (and are Public — see below), Excel VBA Sub procedures are still available to the user of a spreadsheet. Therefore, of the above simple Sub procedures, the Format_Centered_And_Bold Sub procedure would be available to be used in the worksheets of your Exce workbook but the Format_Centered_And_Sized would not (as it has an argument).

For those Sub procedures that are accessible from the workbook, a simple way to run (or execute) the Sub is:

Open up the ‘Macro’ dialog box by either:

  • Clicking the Macros option from the ‘Developer’ tab of the Excel ribbon

or

  • Using the keyboard shortcut Alt + F8 (i.e. press the Alt key and while this is pressed down, press F8).
  • Within the ‘Macro’ dialog box, select the macro you wish to run and click the Run button.
  • Assigning a Keyboard Shortcut to a Sub Procedure

    You can assign a key combination to your Sub procedure, to enable quick and easy execution of the code. To do this:

    Open up the ‘Macro’ dialog box by either:

    • Clicking the Macros option on the ‘Developer’ tab of the Excel ribbon

    or

    • Using the keyboard shortcut Alt + F8 (i.e. press the Alt key and while this is pressed down, press F8).
  • Within the ‘Macro’ dialog box, select the macro you wish to assign a key combination to;
  • Click Options. to open the ‘Macro Options’ dialog box;
  • Type the required keyboard shortcut into the ‘Macro Options’ dialog box;
  • Click OK and then shut down the ‘Macro’ dialog box.
  • WARNING: When assigning a key combination to a macro, take care not to select one of Excel’s predefined key combinations (e.g. CTRL-C). If you do select an existing Excel key combination, this will be overwritten by your macro, and you, or other users, may end up accidentally executing your macro code.

    Scope of VBA Procedures

    In Part 2 of this tutorial, we discussed the scope of variables and constants and the role of the Public and Private keywords. These keywords have the same meaning when applied to VBA procedures:

    Public Sub AddToCells(i As Integer )
    .
    .
    .
    End Sub
    If a procedure declaration is preceded by the keyword Public , this makes the procedure accessible to all other modules in the VBA Project.
    Private Sub AddToCells(i As Integer )
    .
    .
    .
    End Sub
    If a procedure declaration is preceded by the keyword Private , this makes the procedure only available to the current module. It cannot be accessed from any other modules, or from the Excel workbook.

    If no keyword is inserted at the start of a VBA Function or Sub declaration, then the default setting is for the procedure to be Public (i.e. to be accessible from anywhere in the VBA Project). This differs from variable declarations, which are Private by default.

    Early Exit From VBA Function & Sub Procedures

    If you want to exit a VBA Function or Sub procedure before it has run to the end, you can do this using the Exit Function or the Exit Sub command. This is illustrated below, in a simple Function procedure that expects to receive a positive value to work with. If the value received is not positive, the function cannot continue, so it highlights the error to the user and exits the procedure immediately:

    Note that, before exiting the VAT_Amount Function procedure, the above code uses the built-in VBA MsgBox function, to display a box containing a warning message to the user.

    Источник

    Adblock
    detector

    Понравилась статья? Поделить с друзьями:
  • Excel vba sub range
  • Excel vba string to number one
  • Excel vba string to long
  • Excel vba string not in array
  • Excel vba string array to string