Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54
1. Introduction to VBA and VBA editor 2.
Events and Methods
3. Variables and data types 3. Excel objects application, Workbook, worksheet. 4. Control Structures Unit I 5. Control Structures Unit 2 6. Control Structures Unit 3 7. Functions and Sub-procedures 8. Form, form controls and dialog boxes Unit I 9. Form, form controls and dialog boxes Unit II 10. Recording and Debugging Macros 11. Code optimization and documentation 12. Code security and Modules 13. Interaction with Outlook 14. Project Work
Course Content Activating Visual Basic Editor 1 2 1 Click on Developer tab 2 Click on Visual Basic Icon 1 2 3 4 1 VBA Editor 2 Code Window 3 Properties Window 4 Project Window Visual Basic Editor 1 Event Dropdown 2 Objects Dropdown 3 Code Window 4 Method Code Window 1 2 3 4 1 Objects Dropdown 2 Property Name 3 Property Value Properties Window 1 2 3 Definitions Event: a software message indicating that something has happened, such as a keystroke or mouse click
Properties are as in everyday language and technically are fields of objects with dedicated get or set routines.
Methods Actions supported by an object and usually expresses the verbs of the objects. For example, an object of type Window usually would have methods open and close
Object An object is an entity that comprises of properties and methods. Example if car is an object, start, stop are methods. Color , capacity are properties.
Variables and Data types Data types VBA Supports Byte, Boolean, Integer, Long, Currency, Decimal, Single, Double, Date, String, Object, Variant (default) data types
- The Integer and Long data types can both hold positive or negative values. - The Byte data type can hold positive values from 0 to 255 Variable A named storage location that can contain data that can be modified during program execution. Each variable has a name that uniquely identifies it within its scope. A data type can be specified or not. Variable names must begin with an alphabetic character, must be unique within the same scope, can't be longer than 255 characters, and can't contain an embedded period or type-declaration character.
Examples
Dim Name as string Dim age as integer Dim dob as date 1 Key word 2 Variable Name 3 Data type 1 2 3 Variable Declaration and initialization Variable Declaration
Dim Name as string Dim age as integer Dim dob as date
Initialization
Name= Age=0 Dob=#00-00-000#
Assignment
Name = Amitab OR Name = sheet1.range(A1).value Age= 78 OR Age = sheet1.range(A2).value Dob = #10-June-1939# OR Dob = sheet1.range(A3).value
Sample Copy paste Application Private sub Command1_Click()
Name = sheet1.range(A1).value Age = sheet1.range(A2).value Dob = sheet1.range(A3).value
End Sub Private sub Command2_Click()
sheet1.range(C1).value = Name sheet1.range(C2).value= Age sheet1.range(C3).value= Dob
End Sub Dim Name as string Dim age as integer Dim dob as date
Excel Objects Application, Workbook, Sheet, Active worksheet Workbook object A collection of all the Workbook objects that are currently open in the Microsoft Excel application.
Use the Workbooks property to return the Workbooks collection. The following example closes all open workbooks.
Workbooks.Close
Use the Add method to create a new, empty workbook and add it to the collection. The following example adds a new, empty workbook to Microsoft Excel.
Workbooks.Add
Use the Open method to open a file. This creates a new workbook for the opened file. The following example opens the file Array.xls as a read-only workbook.
Workbooks.open FileName:=VBA.xls, Readonly:=True
The ActiveWorkbook property returns the workbook that's currently active.
Excel Objects Application, Workbook, Sheet Application object You use the Application property to return the Application object. After you have a reference to the application, to access the objects under the Application object, you move down the object model hierarchy, for example from Application to Workbook to Worksheet to Cells.
Application.Workbooks(1).Worksheets(1).Cells(1,1)
You can use many of the properties and methods that return the most common user- interface objects, such as the active worksheet without the Application object qualifier. For example, instead of writing the following.
Application.ActiveSheet.Name = Tutorial"
Use Window arrange method to arrange active workbook windows
Application.Windows.Arrange xlArrangeStyleTiled
Excel Objects Application, Workbook, Sheets Sheets object A collection of all the sheets in the specified or active workbook.
Use the Sheets property to return the Sheets collection. The following example prints all sheets in the active workbook.
Sheets.Printout
Use the Add method to create a new sheet and add it to the collection. The following example adds two chart sheets to the active workbook, placing them after sheet two in the workbook.
Use Sheets(index), where index is the sheet name or index number, to return a single Chart or Worksheet object. The following example activates the sheet named "sheet1.
Sheets("sheet1").Activate
4. Control Structures Unit I Copy Paste Application module we saw in the previous session overwrites any data present in the destination cell. Could we prompt the user before overwriting ? Yes following code incorporates that check.
If Sheet1.Range(C1).value <> then
Sheet1.Range(C1).value = CName Sheet1.Range(C2).value = Age Sheet1.Range(C3).value = dob
End if
Above code snippet uses If construct to check if the cell the cell is blank. Syntax of If construct is given below
If <condition> then This block executes if condition is true Else This block executes if condition is false End if 4. Control Structures Unit I You could use logical operators AND, OR, NOT when condition expression is complex For example
If( <condition1> And <condition2> ) then This block executes if both the conditions are true else this block executes if both or one of the condition is false End if
Similarly
If( <condition1> Or <condition2> ) then This block executes if one of the conditions are true else this block executes if one of the condition is false End if
NOT operator negates the condition
4. Control Structures Unit I You could also nest If statements with another If statement as below
If <condition1> then
If <condition2> then
This block executes if both the conditions are true Else
if <condition3> then Executes if both 1 and 2 are false and condition 3 is true End if End if End if
4. Control Structures Unit I When you have multiple conditions Select Case is preferred versus If to reduce complexity of the code structure.
Select Case <variable>
Case value1
Case value2
Case Else
End Select
There is no limit on number of values the <variable> can take. 4. Control Structures Unit 2 What if you need to perform a check on hundreds of cells! Would you write hundred If statements ? Answer is No. you would use a looping construct to scan thrugh the cells.
For <variable> = <start value> to <end value>
Scan statements goes here
Next <variable>
Similar to IF you can use nested For loops
For <variable> = <start value> to <end value>
For <variable> = <start value> to <end value>
Scan statements goes here
Next <variable>
Next <variable>
4. Control Structures Unit 2 When number of iterations are not known you would use While loop
While <Condition>
Statements goes here
Wend
Similar to For loop while loops can be nested as below
While <Condition> While <Condition>
Statements goes here Wend
Wend
Note: It is important that the statements with in a while loop changes the <condition> to false at some point else it will result in infinite loop.
7. Functions and Sub-Procedures In Excel VBA, a set of commands to perform a specific task is placed into a procedure, which can be a function or a subroutine/Procedure. The main difference between a VBA function and a VBA subroutine is that a function returns a result, whereas a subroutine does not.
Therefore, if you wish to perform a task that returns a result (eg. summing of a group of numbers), you will generally use a function, but if you just need a set of actions to be carried out (eg. formatting a set of cells), you might choose to use a subroutine
Arguments In VBA, both functions and subroutines can be passed data via arguments, which are declared in the VBA function or subroutine definition. For example, we might have a VBA subroutine that adds 2 Integers You could supply the value of the integer to the subroutine via an argument, as follows:
Sub Add(a as integer, b as Integer)
msgbox sum is & a+b
End Sub 7. Functions and Sub-Procedures Functions Function are similar to Procedures one difference is that they can return a value.
Private Function AddNum(a As Integer, b As Integer) As Integer
AddNum = a + b
End Function
Note : If you want to exit a VBA function or subroutine before its natural end point, you can do this using the Exit Function or the Exit Sub command.
Default Score of a Function or Procedure is Private
1 Scope of the Function 2 Return type 1 2 3 4 3 Arguments 4 Return value To invoke this Function you would use
Dim mytotal as integer
Mytotal = AddNum(45,89)
7. Functions and Sub-Procedures Optional Arguments You can also define VBA functions or subroutines to have Optional arguments. These are arguments that the user can supply if they want, but if they are omitted, the procedure will still work. To return to the example above, if we wanted to make the supplied integer optional, this would be declared as follows:
Sub Weekday(Optional cday As Integer)
Select Case cday
Case 1 MsgBox "Sunday" Case 2 MsgBox "Monday" Case 3 MsgBox "Tuesday" Case 4 MsgBox "Wednesday" Case 5 MsgBox "Thursday" Case 6 MsgBox "Friday" Case 7 MsgBox "Saturday" Case Else you could use ismissing() function to check if argument is blank
End Select End Sub To invoke this procedure you can use below
Call Weekday() returns current day
Call Weekday(2) returns Monday 7. Functions and Sub-Procedures Passing Arguments By Value and By Reference When arguments are passed to VBA functions, they can be passed in two ways: ByVal - The argument is passed by Value. This means that just the value (ie. 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 actual 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. We can specify whether an argument is passed to a VBA function by value or by reference by using the ByVal or the ByRef keyword when defining the procedure. This is shown below:
Sub add(ByVal a As Integer, ByVal b As Integer)
End Sub
Sub add(ByRef a As Integer, ByRef b As Integer)
End Sub 8. Form, form controls and dialog boxes Unit I You can Form control to present a neat user interface like any other windows application. You can add a form by selecting UserForm from Insert Menu or by right clicking on any object in the project Window as shown below 8. Form, form controls and dialog boxes Unit I You can use Form control tool box to insert various controls on the form. Toolbox should be visible once you insert the form, if not, use the Toolbox icon to activate, as shown below 1 2 3 4 1 Form control in design mode 2 Icon to activate Toolbox 3 Form Control Toolbox 4 Form Controls 8. Form, form controls and dialog boxes Unit I Create a login from use Label, Textbox and Command button controls from the toolbox. 1 2 3 4 Use Property window to change the caption property of Form, Labels and command button. Change form Name to frmLogin. 8. Form, form controls and dialog boxes Unit I Double click on ThisWorkbook object use workbook open event to write the code fromLogin.show 1 Number 1 in the above code is an optional parameter that makes the form Model. Means you need enter credentials before accessing the workbook. 8. Form, form controls and dialog boxes Unit I Save the workbook as Excel Macro-Enabled Workbook. Note: To be able to execute macros you need save workbooks in (.xlsm) Excel Macro-Enabled Workbook format. 9. Form, form controls and dialog boxes Unit II The Shopping Cart Application 1 Radio button 1 2 4 5 7 3 6 2 Check box 3 Frame 4 List box 5 Combo/dropdown box 6 Command button 7 Label 8. Form, form controls and dialog boxes Unit II The Shopping Cart Application Radio buttons allows you to select one option from a group. Code below is used check if a option button is checked.
If OptionButton.Value = True Then
End if
Check boxes allows you to select multiple options from a group. Code below is used check if a Check box is checked.
If Checkbox.Value = True Then
End if
List box and Combo box allows you to display list of options. List box allows you to select multiple options . To add /Remove items into list box you can use
Listbox.additem New item
lstItems.RemoveItem 1 where 1 is the item index
8. Form, form controls and dialog boxes Unit II The Shopping Cart Application Alternatively you can use RowSource property to add data in to list/combo boxes
listbox.RowSource = Sheet1!a1:a10
ComboBox.RowSource=Sheet1!a2:a10
To add multiple columns of data, first set Column Count property.
ComboBox.ColumnCount= 3
comboBox.RowSource=sheet1!a2:c10
Use Clear method to clear contents of List/Combo box
ComboBox.clear
ListBox.Clear
10. Recording and Debugging Macros
In Excel 2007/2010, all macro - related commands are located on the Developer tab of the ribbon. 1 Record/Stop Recording 2 View/assign shortcut keys to Macros 3 View Code 1 2 3 Macros are stored in Module to view code double click on Modules and select Module1 (default name).
Note: you can Insert/rename modules to suit your application 10. Recording and Debugging Macros
Record Macro will display below dialog 1 Macro Name type a name to suit its application/ leave it as Macro1 2 Assign a shortcut by pressing <shift> + <any alphabet>, you can use this later to runt the macro you are recording. 3 Select location to store the macro 3 Description Describe functionality of the Macro 1 2 3 4 10. Recording and Debugging Macros
Type numbers in columns A, B and C as below, Click Record Macro Insert Sum() function in cell A4 Copy sum() formula to cell B4 and C4 Click Stop Recoding Double Click on Module1 to view code 10. Recording and Debugging Macros
Then AddNum macro you recorded always adds numbers in first three cells of column A B and C no matter which cell is active.
Alternatively you could write your own code that is more useful.
Public Sub addnumbers() keyboard shortcut : Ctrl+Shift+z
Dim CurCol As String CurCol = Mid(ActiveCell.Address, 2, 2)
Code above add all numbers in the active column when you press the key combination <Ctrl> + <Shift> + <Z> 10. Recording and Debugging Macros
You could assign a Macro to a command button by using form controls with out writing single line of code! From Insert dropdown Select Command button under Form Control and draw a button the sheet. From the window that pops up you can select the macro that you want to assign or you can click Record to record a new macro that will get assigned to button you just inserted. 10. Recording and Debugging Macros
You can use Form controls to build user interface with out writing any code. For example Create a drop down with list of items Draw dropdown control, right click and select format control , Enter list range in the Input Range. Assign a cell to Cell link this is used to find/take some action based on user selection. The cell link will contain the index of the item user selects from the dropdown. 11. Code optimization and documentation
This section lists some suggestions and strategies for optimizing your Visual Basic For Applications (VBA) code, so that it will run faster. There are few absolute rules for optimizing VBA; you'll see the best increases in performance by streamlining the basic logic
Accessing Cells In A Range
You do not need to use the .Cells method to access specific cells in a range. For example, you can use
Range("MyRange")(1,2) rather than Range("MyRange").Cells(1,2)
VBA will allow you reference cells with [A1] rather than Range("A1"). While the [A1] syntax is easier to type, it is slower to execute than the Range("A1") syntax.
11. Code optimization and documentation
Calculation Mode
Normally, Excel will recalculate a cell or a range of cells when that cell's or range's precedents have changed. This may cause your workbook to recalculate too often, which will slow down performance. You can prevent Excel from recalculating the workbook by using the statement:
Application.Calculation = xlCalculationManual At the end of your code, you can set the calculation mode back to automatic with the statement:
Application.Calculation = xlCalculationAutomatic Remember, though, that when the calculation mode is xlCalculationManual, Excel doesn't update values in cells. If your macro relies on an updated cell value, you must force a Calculate event, with the .Calculate method, which may be applied to either a specific range (Range("MyRange").Calculate) or to the entire workbook (Calculate).
11. Code optimization and documentation
Collection Indexes
An individual item of a collection object may be accessed by either its name or by its index into the collection. For example, if you have three worksheets ("Sheet1", "Sheet2", and "Sheet3") in a workbook ("MyWorkbook"), you can reference "Sheet2" with either
Worksheets("Sheet2") or Worksheets(2)
In general, the index number method (Worksheets(2)) is considerably faster than the index name method (Worksheets("Sheet2")).
However, the number and order of items in a collection may change, so it is usually safer and easier to refer to items in a collection by their name, rather than their index number.
11. Code optimization and documentation
Collection Indexes
An individual item of a collection object may be accessed by either its name or by its index into the collection. For example, if you have three worksheets ("Sheet1", "Sheet2", and "Sheet3") in a workbook ("MyWorkbook"), you can reference "Sheet2" with either
Worksheets("Sheet2") or Worksheets(2)
In general, the index number method (Worksheets(2)) is considerably faster than the index name method (Worksheets("Sheet2")). However, the number and order of items in a collection may change, so it is usually safer and easier to refer to items in a collection by their name, rather than their index number.
Constants
Whenever you can, declare values as constants, rather than variables. Since their values never change, they are evaluated only once when your code is compiled, rather than each time they are used at run time. 11. Code optimization and documentation
Early Binding
This is closely tied with Specific Object Type Declaration. If you're going to work with another application, such as Word, declare your OLE object directly, rather than as an Object type variable. By doing so, a great deal of overhead is done at compile time ("Early Binding") rather than at run time ("Late Binding"). For example, use Dim WordObj As Word.Application rather than Dim WordObj As Object
Range Objects Not Selection Object
Generally, it is not necessary to select a range before working with it. For example, it is more efficient to use
Range("A1").Font.Bold = True
Rather than
Range("A1").Select Selection.Font.Bold = True 11. Code optimization and documentation
Screen Updating
You can turn off screen updating so that Excel does not update the screen image as your code executes. This can greatly speed up your code.
Application.ScreenUpdating = FALSE Be sure to restore the setting to True at the end of your macro. Older version of Excel would automatically restore the setting; Excel97 does not.
Simple Objects Rather Than Compound Objects If you've got to make repeated references to an object, such a range, declare an object of that type, set it to the target object, and then use your object to refer to the target. For example,
Dim MyCell As Range Set MyCell = Workbooks("Book2").Worksheets("Sheet3").Range("C3") '.... MyCell.Value = 123 By referring directly to MyCell , VBA can access the object directly, rather than resolving the complete path to the object each time. This method is useful only when you are accessing an object several times during code execution. 11. Code optimization and documentation
WITH Statements If you are using several statement in a row that apply to the same object, use a WITH statement, rather than fully qualifying the object each time. For example,
With Worksheets("Sheet1").Range("A1") .Font.Bold = True .Value = 123 End With
Worksheet Functions You can use Excel's standard worksheet functions in your VBA code, rather than writing the functions in VBA. Since these are fully executable instructions in native code, rather than interpreted VBA code, they run much faster. For example, use
rather than For Each C In Range("A1:A100") MySum = MySum + C.Value Next C
11. Code optimization and documentation
Code Documentation
You are expected to fully document your code. Every module should have a name, a brief one-line description, and a detailed description of the algorithm. All methods also require descriptions of all inputs and outputs. If applicable, you should also note any short comes - things that could go wrong or things that the code doesn't address. Put assumptions in the short comes section. 12. Code security and Modules
Module
As we saw in earlier sessions recording a Inserts a module and the code is stored in it. Alternatively you can insert a Module from Insert menu as shown below 12. Code security and Modules
Use Export option to Save your Module as a stand alone file. This stand alone file can be imported into other workbooks. Use Remove option to delete Module form Workbook. 12. Code security and Modules
Use VBA Project properties to lock/protect your code as shown below. 13. Interaction with Outlook
Microsoft Outlook supports Automation, you can control Outlook from any program that is written with Microsoft Visual Basic. Automation provides a standard method for one application to access the objects, methods, properties, and events of other applications that support Automation.
The Outlook object model provides all of the functionality necessary to manipulate data that is stored in Outlook folders, and it provides the ability to control many aspects of the Outlook user interface (UI).
To start an Outlook Automation session, you can use either early or late binding. Late binding uses either the Visual Basic GetObject function or the CreateObject function to initialize Outlook. For example, the following code sets an object variable to the Outlook Application object, which is the highest-level object in the Outlook object model. All Automation code must first define an Outlook Application object to be able to access any other Outlook objects.
Dim objOL as Object Set objOL = CreateObject("Outlook.Application")
13. Interaction with Outlook
To use early binding, you first need to set a reference to the Outlook object library. Use the Reference command on the Visual Basic for Applications (VBA) Tools menu to set a reference to Microsoft Outlook xx.x Object Library, where xx.x represents the version of Outlook that you are working with. You can then use the following syntax to start an Outlook session.
Dim objOL as Outlook.Application Set objOL = New Outlook.Application
Most programming solutions interact with the data stored in Outlook. Outlook stores all of its information as items in folders. Folders are contained in one or more stores. After you set an object variable to the Outlook Application object, you will commonly set a NameSpace object to refer to MAPI, as shown in the following example.
Set objOL = New Outlook.Application Set objNS = objOL.GetNameSpace("MAPI") Set objFolder = objNS.GetDefaultFolder(olFolderContacts)
13. Interaction with Outlook
Once you have set an object variable to reference the folder that contains the items you wish to work with, you use appropriate code to accomplish your task, as shown in the following example.
Sub CreateNewDefaultOutlookTask() Dim objOLApp As Outlook.Application Dim NewTask As Outlook.TaskItem ' Set the Application object Set objOLApp = New Outlook.Application ' You can only use CreateItem for default items Set NewTask = objOLApp.CreateItem(olTaskItem) ' Display the new task form so the user can fill it out NewTask.Display End Sub
Above example creates a outlook task, example below create a mail.
Dim myOlApp As New Outlook.Application Dim myItem As Outlook.MailItem Set myItem = myOlApp.CreateItem(olMailItem)
13. Interaction with Outlook
Use Delegate object to add mail Recipients
Dim myDelegate As Outlook.Recipient
Set myDelegate = myItem.Recipients.Add exceltech@gmail.com
myDelegate.Type = olTo To field on mail item
myItem.Body = Hi this mail is sent from a macro email body
myItem.Attachments.Add <filename> add attachments
myItem.Send Send email
14. Project Mailing Application
Create a mailing application that reads recipient list from an excel file. Application should provide an option to attach files with some custom text pre fix to the file Names. Application interface should look like
14. Project Mailing Application
When you click on the buttons it should display file open dialog box as below