My VBA
My VBA
If we don’t put the End sub in the program we will get the Expected End sub Error message
Input Box
Input Box is a built in function to read the input. it allow the values from the user .After entering the
values in input Box, if the user clicks the OK button or presses ENTER on the keyboard, the InputBox
function will return the text in the text box. If the user clicks on the Cancel button, the function will
return an empty string ("").
Note: we use a variable of type Variant here because a Variant variable can hold any type of value. This
way the user can enter text, numbers, etc.
Syntax :
InputBox(prompt,[title][,default][,xpos][,ypos][,helpfile,context])
Or
InputBox(prompt,[title][default])
Title - An Optional Parameter. A String expression displayed in the title bar of the dialog box. If
the title is left blank, the application name is placed in the title bar.
Default - An Optional Parameter. A default text in the text box that the user would like to be
displayed.
XPos - An Optional Parameter. The Position of X axis which represents the prompt distance
from left side of the screen horizontally. If left blank, the input box is horizontally centered.
YPos - An Optional Parameter. The Position of Y axis which represents the prompt distance from
left side of the screen Vertically. If left blank, the input box is Vertically centered.
helpfile - An Optional Parameter. A String expression that identifies the Help file to use to
provide context-sensitive Help for the dialog box.
context - An Optional Parameter. A Numeric expression that identifies the Help context number
assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must
also be provided.
Here Prompt is : Enter a Number – it is required field , and it is the work name.
The above error comes because we missed the Double Quotations for the strings that are defined in
range object.
Click Insert-Module
Note: code placed into a module is available to the whole workbook. That means, you can select Sheet2
or Sheet3 and change the background color of these sheets as well.
Relative reference recording of macros will gives the result in any of the cells which we selected when
we run the macro.
FormulaR1C1
Cell addresses consist of a column letter and arrow number. To refer to a cell, enter the column letter
followed by the row number, for example "=B2" to refer to the cell which is the intersection of column
"B" with row "2".
Absolute references have letters and numbers. Relative references have a dollar in front of the letter or
number.
A1 Notation
This is the default method used for creating cell references to other cells.
R1C1 Notation
This is another way to create cell references which uses numbers for both the rows and columns.
Cell References are displayed in terms of their relationship to the cell that contains the formula rather
than their actual position in the grid.
Cells are referred to by relative notation. Absolute references have numbers. Relative references have
numbers in square brackets.
The above formulas will be changed to the following when you switch to R1C1 notation.
Macro Security
The mother of all objects is Excel itself. We call it the Application object. The application object contains
other objects. For example, the Workbook object (Excel file). This can be any workbook you have
created. The Workbook object contains other objects, such as the Worksheet object. The Worksheet
object contains other objects, such as the Range object.
This code not executed error message came while executing
You can refer to a member of the collection, for example, a single Worksheet object, in three ways.
2. Using the index number (1 is the first worksheet starting from the left).
Worksheets(1).Range("A1").Value = "Hello"
3. Using the CodeName. Here code name is project name in the VBA projects not Excel sheets.
Sheet1.Range("A1").Value = "Hello"
Note: the CodeName remains the same if you change the worksheet name or the order of your
worksheets so this is the safest way to reference a worksheet. Click View, Properties Window to change
the CodeName of a worksheet. There is one disadvantage, you cannot use the CodeName if you
reference a worksheet in a different workbook.
Note: the Add method of the Worksheets collection creates a new worksheet.
2. The Count property of the Worksheets collection counts the number of worksheets in a workbook.
MsgBox Worksheets.Count
Note: the Count property of the Workbooks collection counts the number of active workbooks.
Path and FullName
The Path property in Excel VBA returns the complete, saved path to the workbook (Excel file).
The FullName property in Excel VBA returns the complete, saved path, including the name of the
workbook.
Points to be remember :
Situation:
Add the following code lines to the command button:
1. First, we declare two objects and one variable. One object of type Workbook we call book, one object
of type Worksheet we call sheet, and a variable of type String we call text.
Dim book As Workbook, sheet As Worksheet, text As String
2. We want to loop through all open workbooks. To achieve this, add the following code line:
For Each book In Workbooks
3. We write the text "Workbook: ", the name of the workbook, and the text "Worksheets: "" to the
variable text.
text = text & "Workbook: " & book.Name & vbNewLine & "Worksheets: " & vbNewLine
Note: you can use the & operator to concatenate (join) elements. To start a new line, you can use
vbNewLine.
4. To loop through all the worksheets of a workbook, add the following code line:
For Each sheet In book.Worksheets
10. Test the program. Before you click on the command button, give your worksheets some descriptive
names and open another blank workbook.
Result:
Sales Calculator
Below we will look at a program in Excel VBA that calculates the total sales of each employee over a
period of three years.
Situation:
The other two sheets have the same setup, but with different combinations of months and employees,
and different sales numbers. There are several ways to calculate the total sales of each employee in
Excel, but we will see that it can be done in Excel VBA very easily.
Place a command button on your worksheet and add the following code lines:
1. First, we declare three variables and one Worksheet object. One variable of type String we call
employee, one variable of type Integer we call total, one Worksheet object we call sheet, and one
variable of type Integer we call i.
Dim employee As String, total As Integer, sheet As Worksheet, i As Integer
2. We initialize two variables. We initialize the variable total with value 0. We use the InputBox function
to get the employee name from the user.
total = 0
employee = InputBox("Enter the employee name (case sensitive)")
3. After the user has entered an employee name, we want to calculate the total sales of this employee.
The workbook consists of three sheets. We want a program that can still be used if sheets are added in
the future. Therefore we use the following code line:
For Each sheet In Worksheets
5. If the entered employee name matches with the employee name in column B, Excel VBA adds the
sales number to the variable total. Add the following code lines:
If sheet.Cells(i, 2).Value = employee Then
total = total + sheet.Cells(i, 3).Value
End If
Download Book1.xls, Book2.xls, Book3.xls, Book4.xls and Book5.xls and add them to "C:\test\"
Situation:
Add the following code lines to the command button:
1. First, we declare two variables of type String, a Worksheet object and two variables of type Integer.
Dim directory As String, fileName As String, sheet As Worksheet, i As Integer, j AsInteger
3. Initialize the variable directory. We use the Dir function to find the first *.xl?? file stored in this
directory.
directory = "c:\test\"
fileName = Dir(directory & "*.xl??")
Note: the Dir function supports the use of multiple character (*) and single character (?) wildcards to
search for all different type of Excel files.
4. The variable fileName now holds the name of the first Excel file found in the directory. Add a Do While
Loop.
Do While fileName <> ""
Loop
5. Initialize the variables of type Integer and add the name of the Excel file to the first column of row i.
i=i+1
j=2
Cells(i, 1) = fileName
6. There is no simple way to extract data (or sheet names) from closed Excel files. Therefore, we open
the Excel file.
Workbooks.Open (directory & fileName)
7. Add all the sheet names of the Excel file to the other columns of row i.
For Each sheet In Workbooks(fileName).Worksheets
Workbooks("files-in-a-directory.xls").Worksheets(1).Cells(i, j).Value = sheet.Name
j = j + 1
Next sheet
9. The Dir function is a special function. To get the other Excel files, you can use the Dir function again
with no arguments.
fileName = Dir()
Note: when no more file names match, the Dir function returns a zero-length string (""). As a result,
Excel VBA will leave the Do While loop.
Result: