Creating Macros Using VBA
Assigning a Macro to a Button Display the Forms toolbar. Click the Button icon. Click and drag the mouse pointer to specify the position and size of button. Click the macro name you are assigning to this button. Click OK. Type an appropriate title for the button. Click outside the button to deselect it.
Elements of VBA Editor Project Explorer Properties Window Code Window
The Project Explorer A project is a collection of macros, worksheets, forms for data entry, and other items that make up the customized application you’re trying to create. The Project Explorer is a way to manage your projects. It is a window in the VBA editor that displays a hierarchical list of all currently opened projects and their contents. An object is an element of a custom application, such as a worksheet, a macro, or the workbook.
Docking and Undocking The Project Explorer window is dockable, you can drag it to the edge of the screen, and it will remain on top, above other windows. Undocking- right-click the window’s title bar, deselect dockable from the shortcut menu. Docking- Click Tools, Options, Docking tab, select the check box for the window you want to dock.
Changing the Name of Your Project Select the Project name in the Project Explorer window. Click Tools, click the Project Name’s Properties, click the General tab, type a new name in the Project Name box.
The Properties Window A property is an attribute of an object that defines one of its characteristics, such as name, size, color, or location on the screen. All objects have properties. Use the Properties Window to view a list of properties for any object.
Changing the Name of a Worksheet Click the Sheet name in the Project Explorer for the worksheet that you want to change the name for. Click the Alphabetic tab in the Properties window. Beside the Name property, select the value. Type a new name. Hit Enter.
Modules A module is a collection of VBA macros. You can use modules to group macros according to the type of tasks they perform. To re-name a macro module: Select the module in the PE window. Double-click the name of the module in the Properties window. Type a new name. Press Enter.
The Code Window Displays the VBA macro code of any item in the Project Explorer. Sub/End Sub- mark the beginning and end of a macro. Comments- statements that explain what is happening in the macro. Preceded by an apostrophe. Body of the macro- series of statements b/n Sub and End Sub representing the VBA translation of the actions performed while recording the macro.
Procedures VBA supports 3 kinds of procedures: Sub procedure- performs an action on your project or workbook (ex: clearing cells, formatting cells, displaying a chart). Function procedure- returns a value. Property procedure- is a more advanced subject when you want to create customized properties for the objects in your project.
Sub Procedures General syntax: Sub Procedure_Name(parameters) Visual Basic commands and comments End Sub Example Sub Annual_Report( ) ‘Annual_Report Macro ‘This macro displays the Annual Report worksheet. Sheets(“Annual Report”).Select Range(“A1”).Select End Sub Comments- statements that describe the behavior of the procedure. They begin with an apostrophe and usually appear in green type. The procedure lists the VBA commands needed to carry out the macro.
Inserting a New Procedure In the Code Window, click Insert, click Procedure. Type a name in the Name in the Name box. Click the Sub button (to create a sub procedure) or Function button (to create a private function). Click the Public button (to make it available to other modules). Click OK. Or double-click on the desired sheet and enter the reserve word Sub followed by the macro’s name.
Objects VBA is an object-oriented programming language- it performs tasks by manipulating objects. An object can be a cell, worksheet, or Excel application. Objects have attributes (characteristics) and methods (actions). Collection objects- a group of objects.
Describing Excel Objects Excel Object Range Name Chart ChartObject Worksheet Workbook VBAProject Application Description A cell in a worksheet A range name in a workbook A chart in a workbook A chart embedded within a worksheet A worksheet in a workbook An Excel workbook A VBA project The Excel application itself
VBA Code Examples VBA Code Range(“A1:B10”) Names(“FillerA”) ChartObject(3) Charts(3) Sheets(“Sample Data”) Workbooks(“Datalia2”) Windows(2) Description The collection of cells in the cell range A1:B10 The FillerA range name The third embedded chart in a worksheet The third chart sheet in a workbook The Sample Data worksheet The Datalia2 workbook The second open Excel workbook window
Specific Object Names Special Object Name ActiveCell ActiveChart ActiveSheet ActiveWindow ActiveWorkbook ThisCell ThisWorkbook Description The currently selected cell The currently selected chart The currently selected sheet The currently selected window The current workbook The cell from which a custom function is being run The workbook containing the macro code currently running
Properties Properties- the attributes that distinguish an object. To change the property of an object, use the syntax in VBA: object.property = expression
Selected Objects and Their Properties Object Properties Range Address Comment Formula Value Name Refers To Value Worksheet Name Visible Chart ChartTitle ChartType HasLegend Workbook HasPassword Name Path Saved Description The cell reference of the range A comment attached to the cell The formula entered into the cell The value of the cell The cell(s) to which a range name refers The value of the cell referenced to by the range name The name of the worksheet Whether the worksheet is visible or hidden The text of the chart’s title The type of chart Whether the chart has a legend Whether the workbook has a password The name of the workbook The folder and drive in which the workbook is stored Whether the workbook has been saved
VBA Code Application VBA Code ActiveCell.Value=23 Range(“A5”).Formula=Sum(A1:A4) Worksheets(“Raw Data”).Name=”Sample Data” ActiveWorkbook.Password=” powder” Application.StatusBar=”Running macro …” Description Changes the value of the active cell to 23 Changes formula to Sum(A1:A4) Changes Worksheet name to Sample Data Changes current workbook password to powder Display text “Running macro … in status bar-
Examples – Changing Properties Worksheets(“Grades”).Name = “Old Grades” changes the Name property of the “Grades” worksheet to “Old Grades.” Range(“G5”).Value = changes the Value property of cell G5 to Range(“H5”).Formula = “=G5-F4” changes the Formula property of cell H5 to =G5-F4 Worksheets(“Sheet 1”).Visible = False hides sheet 1. Change to True to make visible again. Activecell.Value=15 changes the value of the active cell to 15.
A Method is an action that can be performed on an object. Object Method Range Clear Copy Merge Worksheet Delete Select Workbook Close Protect Save Chart Copy Select Delete Charts Select Worksheets Select Description Clear all formats and values in the range Copies the values in the range to the Clipboard Merges the cells in the range Deletes the worksheet Selects and displays the worksheet Closes the workbook Protects the workbook Saves the workbook Copies the chart Selects the chart Deletes the chart Selects the chart sheets in the workbook Selects the worksheets in the workbook
Selected Assignment Statements VBA Code Range(“A1”).Copy Destination:=Range(“A5”) Range(“A1”).AddComment Text:=”Total Assets” Sheets(“Sheet 1”).Move After:=Sheets(“Sheet 3”) ActiveWorkbook.SaveAs Filename:=”Data2” ActiveWorkbook.Protect Password=”powder” Description Copy contents of A1 to A5 Adds comment to cell A1 Move Sheet 1 to right of Sheet 3 Saves active workbook as Data2 Protects workbook using powder
Using Methods With Objects VBA Code Range(“A1:B1”).Clear Range(“A1”).Select Range(“A1”).AddComment(“Total Assets”) Sheets(“Statistics”).Select ActiveSheet.Delete ActiveWorkbook.Save Workbooks(“Data1”.SaveAs(“Data2”) ActiveWorkbook.Protect(“powder”) Description Clears contents of A1:B1 Selects cell A1 Adds comment to A1 Displays Statistics sheet Deletes current sheet Saves current workbook Renames workbook Data1 to Data2 Protect workbook with powder password
Variables A variable is a named storage location containing data that you can retrieve and modify while the program is running. A variable name identifies a variable. The key word Dim is used to create variables Syntax for storing a variable: variable = expression Example: Total = 987 (Sets the value of the Total variable to 987) Variable Data Types: –Boolean is set to True or False; False=0 –Integer ranges from -32,768 to 32,767 –Long Integer ranges from -2 billion to 2 billion –Single is single-precision floating-point numbers, with six digits of accuracy –Double is double-precision floating-point numbers, with 14 digits of accuracy –Variant can store any type of information –Currency allows fifteen digits to the left of the decimal point and 4 digits to the right of decimal point (note: use when calculating money amounts) Variable Naming Conventions: –Must be at least 1 character in length, but no more than 255 characters in length –First character must be a letter, after that they can be letters, numbers, or underscore –Cannot contain periods or spaces –Cannot use VB key words: example- Dim, Integer, Sub, or Private Initial Values: –Numeric data types are automatically assigned value of 0. –String variables are assigned an empty string. –Boolean variables are assigned False Date variables start with time value at 12:00:00 am Color codes: Green=comments; Blue=reserved words; Red=syntax error
Arithmetic and Logical Operators Arithmetic Operations –+ Addition –- Subtraction –* Multiplication –Mod Modulas –/ Division –\ Integer Division –^ Exponentiation Logical Operators And Or Not Order of Operation –Parentheses () –^ –Negation - –*,/ –\ –Mod –+,-