0% found this document useful (0 votes)
42 views

My VBA

The document discusses using InputBox in VBA. InputBox allows users to enter input which can be returned as a string. The summary includes the syntax and parameters of InputBox: InputBox prompts the user to enter text, which is returned as a string if the user clicks OK. It includes optional parameters for the prompt, title, default text, and screen position. Common parameters include the required prompt parameter and optional title and default text parameters.

Uploaded by

Devotees Adda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

My VBA

The document discusses using InputBox in VBA. InputBox allows users to enter input which can be returned as a string. The summary includes the syntax and parameters of InputBox: InputBox prompts the user to enter text, which is returned as a string if the user clicks OK. It includes optional parameters for the prompt, title, default text, and screen position. Common parameters include the required prompt parameter and optional title and default text parameters.

Uploaded by

Devotees Adda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

If we declare the variables twice is same program for same purpose we will get the Duplicate

Declaration in current scope error message comes.

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

 Prompt – It is A Required Parameter. It is A String that is displayed as a message in the dialog


box regarding the input.  If the message extends to more than a line, then we can separate the
lines using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each
line.

 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.

Here Title is : Daama


https://www.tutorialspoint.com/vba/vba_message_box.htm
Swapping Values Between Cells

The above error comes because we missed the Double Quotations for the strings that are defined in
range object.

Ex: Range(A1) Range(“A1”)

Run Code from a Module

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.

Use Relative References


By default, Excel records macros in absolute mode. However, sometimes it is useful to record macros
in relative mode.

Recording in Absolute Mode

1. click on record macro


2. select cell B3 and type the Sales, Production, and Logistics in consecutive rows
3. click stop recording
4. Now delete the words you entered in the rows
5. Select any cell and run the recorded macro.

Recording in Relative Mode

1. select relative references


2. Select any cell
3. Record macro
4. select cell B3 and type the Sales, Production, and Logistics in consecutive rows
5. click stop recording
6. Select any cell and run the recorded macro.

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.

This example illustrates the difference between A1, R1C1 and R[1]C[1] style in Excel VBA.

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

1. On the Developer tab, click Macro Security.


2. Here you have four options. The first option will disable all macros. The second option will
always ask you to enable a macro. The third option will only allow macros with a digital
signature to run, and ask you to enable others. The fourth option will enable all macros.
Work Book and Work Sheet Object. 
Object Hierarchy
In Excel VBA, an object can contain another object, and that object can contain another object, etc. In
other words, Excel VBA programming involves working with an object hierarchy.

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

Note: the objects are connected with a dot.


Collections
You may have noticed that Workbooks and Worksheets are both plural. That is because they are
collections. The Workbooks collection contains all the Workbook objects that are currently open. The
Worksheets collection contains all the Worksheet objects in a workbook.

You can refer to a member of the collection, for example, a single Worksheet object, in three ways.

1. Using the worksheet name.


Worksheets("Sales").Range("A1").Value = "Hello"

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.

Properties and Methods


Now let's take a look at some properties and methods of the Workbooks and Worksheets collection.
Properties are something which an collection has (they describe the collection), while methods do
something (they perform an action with an collection).

1. The Add method of the Workbooks collection creates a new workbook.


Workbooks.Add

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

Result when you click the command button on the sheet:

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 :

1. Path Property : shows the path


2. Full Name Property : shows the path and full name

Loop through Books and Sheets (Not executed)


 Below we will look at a program in Excel VBA that loops through all open workbooks and worksheets,
and displays all the names.

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

5. We write the names of the worksheets of a workbook to the variable text.


text = text & sheet.Name & vbNewLine

6. Close the second loop.


Next sheet

7. Add a white line.


text = text & vbNewLine

8. Don't forget to close the first loop.


Next book

9. Finally, we display the variable text using a MsgBox.


MsgBox text

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

4. We start another For Next loop.


For i = 2 To 13

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

6. Don't forget to close both loops.


    Next i
Next sheet
7. Finally, we display the total sales of the employee using a msgbox.
MsgBox "Total sales of " & employee & " is " & total

8. Test the program.

Result for David:

Files in a Directory not Executed


 Below we will look at a program in Excel VBA that loops through all closed workbooks and
worksheets in a directory, and displays all the names.

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

2. To avoid screen flicker, turn off screen updating.


Application.ScreenUpdating = False

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

Add the following code lines (at 5, 6, 7, 8 and 9) to the 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

8. Close the Excel file.


Workbooks(fileName).Close

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.

10. Turn on screen updating again (outside the loop).


Application.ScreenUpdating = True

11. Test the program.

Result:

You might also like