This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
VBA Training
CONFIDENTIAL AND PROPRIETARY INFORMATION
This presentation and the information contained herein are confidential and proprietary,and are intended for review only by the employees of marketRx, Inc. All other reviewers must have the prior written consent of marketRx, Inc.
A macro is a short program written using VBA that can be used to carry out a specific task
VBA is the language that Excel macros are written in. It is a programming language that is included with all of the Microsoft Office applications e.g. Word, Access, PowerPoint, Excel as well as others. VBA is a subset of Microsoft Visual Basic, an extremely popular programming
Security levels – control how Excel handles suspect macros. High: causes Excel to disable all
macros either lacking a digital signature or containing an invalid one.
Medium: Excel prompts the user to enable the macro or not if it lacks a digital signature. Certificates with invalid signatures are automatically disabled. Macros containing a valid signature are automatically enabled.
Low: All macros are enabled.
Macros without a digital signature are disabled by default in Excel 2000.
To enable macros, go to “Tools Options Macro Security” and then select “medium”.
Add a Button in an Excel sheet Display the Forms toolbar. Click the Button icon. Click and drag the mouse pointer to specify the position and size of button. Select the macro name you are assigning to this button from the Assign Macro
dialog box. Click OK.
Change the Name of the Button Highlight the button (Hit Ctrl and click on the button). Highlight the label on the button. Type a new name for the button. Click outside the button.
If you pass an argument by reference when calling a procedure, the procedure access to the actual variable in memory. As a result, the variable's value can be changed by the procedure.
Passing by reference is the default in VBA. If you do not explicitly specify to pass an argurment by value, VBA will pass it by reference. The following two statements yield the same outcome.
Sub AddNo(ByRef x as integer)Sub AddNo(x as integer)
Here is an example to show the by reference behavior. The sub procedure, TestPassing 1 calls AddNo1 by reference and display "60" (50 + 10) on the message box.
The following example shows the by value behavior. The sub procedure, TestPassing 2 calls AddNo2 by value and display "50" on the message box.
Sub TestPassing1()Dim y As Integery = 50AddNo1 yMsgBox y
End Sub
Sub AddNo1(ByRef x As Integer)x = x + 10
End Sub
Sub TestPassing2()Dim y As Integery = 50AddNo2 yMsgBox y
Variables are used for temporary storage of values
Declare variables with Dim You have to state the variables data type The declaration have to be made before using the variable Example: Dim NumItems As Integer
Variables do not have to be defined in VBA, but it is good programming practice to define them To force the definition of variables, at the top of the module window type the
following:• Option Explicit
To force Option Explicit for all Modules: Tools Options Check “Require Variable Declaration”
String – for text like “Bob Smith” string literals are enclosed in quotes
Integer – integers in –32768 to 32768 Long – for bigger integers Boolean – only True (-1) or False (0) Double – numbers with decimals Currency – monetary values Date – for dates and times
date literals must be like this: #1/7/2005# Object – specific versions for each object type Variant – let VBA decide how to deal with
If you don’t declare a variable, this is the default data type VBA will use. This should be avoided as much as possible.
Select Case statement is an alternative to the ElseIf statement. This method is more efficient and readable in coding than the “If ... Then ... ElseIf” statement.
Example:
Select Case Grade Case Is >= 90 LetterGrade = "A" Case Is >= 80 LetterGrade = "B" Case Is >= 70 LetterGrade = "C" Case Is >= 60 LetterGrade = "D" Case Else LetterGrade = "Sorry" End Select
The ReDim statement is used to size or resize a dynamic array that has already been formally declared. For example, if you have already declared an array with an element value of 5 and decided to change
the number of the element to 6, you can do the following to resize the array: Redim Arr(6)
ReDim cannot change the type of the array and it can only change the bounds of the array but not the number of its dimensions.
Each time you execute the ReDim statement, all the values currently stored in the array are lost, unless you use “Preserve” keyword, e.g. ReDim Preserve Arr(10).
The size of an array can be determined by the value of a variable – The following code is an example of that:
InputBox – get a single value from the user Syntax: variable = InputBox(Prompt,Title)
Variable is a variable whose value is set based on user entry. Prompt is the message you want to appear in the input box. Title is the text that appears in the title bar of the input box.
Salary=InputBox(“Enter your salary.”, “Application”)
To generate random number from 0 to 1 uniformly, one can use the Rand() function in Excel or the Rnd function in VBA. These two functions are the mother of all
random numbers. You will need either one of these functions to generate random numbers from any probability distributions. Or you can use the random number generator in Analysis ToolPack Add-ins.
The rand() excel formula function before Excel 2003 has a low quality of randomness. The function was changed in Excel 2003 but has a bug. You need to download a fix from Microsoft. It is better to use Rnd() in VBA to generate random numbers for you.
The example on the right generates 5 random numbers and then displays them in a message box:
* CStr() function converts the random numbers into string.
For the previous example, when we close the file, reopen it, and run the sub routine again, the same 5 numbers come up!
The reason why this happens is that the random numbers were actually being generated from the same set of numbers (called seed).
By placing the Randomize statement in the sub routine, the numbers will be generated from a new seed. (Randomize uses the return value from the Timer function as the new seed value.)
Too many programmers become complacent once the code is written and they get a clean compile. These are only the first steps. The most important steps, and the ones programmers like the least, are debugging and testing code.
Three types of Errors Syntax errors: A variety of errors related to entering the code itself. These include
incorrectly spelled keywords, mismatched parentheses, etc. Excel flags your syntax errors and you can't execute your code until they are correct.
Run-time errors: These are the errors that occur while your code is executing. For example, if your code refers to an object that doesn't exist, you'll get a run-time error. Excel displays a message when there is a run-time error.
Logical errors: These are errors that occur through faulty programming. In many cases they will simply produce incorrect results.
Debugging your code is the process of finding and correcting run-time errors and logical errors
We will describe the various debugging resources available in the Visual Basic Editor (VBE) and how to use them. These are basic descriptions of the various diagnostic tools and how to use them. See
The most common use of the debugger is to diagnose the code when a crash is encountered. If no error handling is in place, when an Access application crashes, you or your user are prompted with an End, Debug message box:
A break point is a setting on a line of code that tells VBA to pause execution immediately before that line of code is executed. Code execution is placed in what is called break mode. When a line contains a break point, it is displayed with a brick colored background. Immediately before this line of code is executed, it will appear with a yellow background.
When VBA is in break mode, you can enter commands in to the Immediate Window to display or change the values of variables.
To put a break point on a line of code, place the cursor on that line and press F9 or choose "Toggle Breakpoint" from the Debug menu.
To remove a break point, place the cursor on the line with the break point and press F9 or choose "Toggle Breakpoint" from the Debug menu.
After a break point is encountered, you can resume normal code execution by pressing F5 or choosing "Continue" from the Run menu, or stepping through the code line by line (see next slide).
Normally, your code runs unattended. It executes until its logical end. However, when you are testing code, it is often useful to step through the code line by line, watching each line of code take effect. This makes it easy to determine exactly what line is causing incorrect behavior.
You can step through code line by line by pressing the F8 key to start the procedure in which the cursor is, or when VBA is paused at a break point.
Pressing F8 causes VBA to execute each line one at a time, highlighting the next line of code in yellow. Note, the highlighted line is the line of code that will execute when you press F8. It has not yet been executed.
If your procedure calls another procedure, pressing F8 will cause VBA to step inside that procedure and execute it line by line. You can use SHIFT+F8 to "Step Over" the procedure call. This means that the entire called procedure is executed as one line of code. This can make debugging simpler if you are confident that the problem does not lie within a called procedure.
When you are in a called procedure, you can use CTRL+SHIFT+F8 to "Step Out" of the current procedure. This causes VBA to execute until the end of the procedure is reached (an End Sub or Exit Sub statement) and then stop at the line of code immediately following the line which called the procedure.
VBA also supports "Run To Cursor". This is exactly what it sounds like. It tells VBA to execute code until the line on which the cursor is sitting is reached. When this line is reach, VBA enters break mode. This is similar to putting a break point on a line of code, except that the break point is
temporary. The second time that line of code is executed, code execution does not pause.
Set Next Statement [Ctrl+F9] This command lets you set the next statement as any line in the current procedure including lines you’ve already run. This is extremely powerful and quite amazing when you think about it. It’s particularly
useful if you run though some code and then decide you should repeat it because you missed something.
It’s not always the same as the first run because variables may have changed, but if you understand the situation, it lets you debug again without getting to the same code or situation again.
Show Next Statement Sometimes you examine different procedures as you debug your code, so the Show Next Statement menu command makes it easy to go to the currently highlighted line.
The Immediate Window is a window in the VBE in which you can enter commands and view and change the contents of variables while you code is in Break mode or when no macro code is executing. Break mode is the state of VBA when code execution is paused at a break point (see
Breakpoints, below.
To display the Immediate Window, press CTRL+G or choose it from the View menu.
In the Immediate Window, you can display the value of a variable by using the ? command. Simply type ? followed by the variable name and press Enter. VBA will display the contents of the variable in the Immediate Window. For example,
?ActiveCell.Address$A$10
You can also execute VBA commands in the Immediate Window by omitting the question mark and entering the command followed by the Enter key:
The Locals Window displays all the variables in a procedure (as well as global variables declared at the project or module level) and their values. This makes it easy to see exactly what
the value of each variable is, and where it changes, as you step through the code.
You can display the Locals Window by choosing it from the View menu. The Locals Window does not allow
you to change the values of variables. It simply displays their names and values.
The Watch Window allows you to "watch" a specific variable or expression and cause code execution to pause and enter break mode when the value of that variable or expression is True (non-zero) or whenever that variable is changed.
To display the Watch Window, choose it from the View menu. To create a new watch, choose Add Watch from the Debug menu. This will display the Add Watch window, shown on the right.
You can use the Debug.Print statement anywhere in your code to display messages or variable values in the Immediate Window. These statements don't require any confirmation or acknowledgement from the user so they won't affect the operation of your code.
'' some code'Debug.Print "Starting Code Section 1"
In Excel 2000 and later, you can use Debug.Assert statements to cause the code to break if a condition is not met. The syntax for Debug.Assert is: Debug.Assert (condition) Example
You cannot completely eliminate bugs in your programs, but there are a few tips that will help you keep them to a minimum.
Use an Option Explicit at the beginning of your module. Doing so will require that you define the data type for every variable that you use. It's a bit more work, but you'll avoid the common error of misspelling a variable name.. And there's a nice side benefit: Your routines will often run faster.
Format your code with indentation. Using indentation to delineate code segments is quite helpful. If you have several nested For...Next loops, for example, consistent indentation will make it much easier to keep track of them all.
Be careful with On Error Resume Next. This statement causes Excel to ignore any errors and continue. In some cases, using this statement will cause Excel to ignore errors that shouldn't be ignored. Your may have bugs and not even realize it.
Use lots of comments. Nothing is more frustrating than revisiting code that you wrote six months ago - and not having a clue as to how it works. Adding a few comments to describe your logic can save you lots of time down the road.
Keep your subroutines and functions simple. Writing your code in smaller modules, each of which has a single, well-defined purpose, makes it much easier to debug them.
Use the macro recorder to help you identify properties and methods. If I can't remember the name or syntax of a property or method, it's often quicker to simply record a macro and look at the recorded code.
Consider a different approach. If you're having trouble getting a particular routine to work correctly, you might want to scrap the idea and try something completely different. In most cases, Excel offers several alternative methods of accomplishing the same thing.
Understand Excel's debugger. Although it can be a bit daunting at first, you'll find that Excel's debugger is an excellent tool. Invest some time and get to know it.
Excel (and the other Office applications) consists of a number of object. An object can be a cell, worksheet, or Excel application.
Macro programming is actually just manipulation of these objects.
When you understand the basic principle, it’s easier to learn how to program other Office programs.
Definition of an object An object is a named part of a computers memory. It has certain features or properties. Like some people have brown hair, others
red hair. It has some functionality or methods. Like people are able to walk or cars able to
Recording Macros is very useful for learning the code to format cells a particular way Incorporate the code from the recorded macro into your code to assist in
formatting cells - eliminate any unnecessary steps excel has added in For example, to formats Cell “A1” to have a blue background and white
Looping Through Worksheets Useful if you want to perform a specific function to each sheet in the workbook
• Specific Formatting• Setting Column Widths• Protecting Cells – If you want to protect worksheets, always make sure you unprotect
the worksheets in the beginning of the code otherwise you will be asked for the password if you try to modify them. At the end of the code you can re-protect all of the worksheets
Screen Updating By setting Screen Updating to False, the user will not see all of the changes that the
code is doing to the workbook until it is finished runningApplication.ScreenUpdating = False
Use a lots of comments A single quote ‘ is used to comment lines of code
Hiding SheetsSheets(“DataDrop").Visible = False
Outputting to Specific SheetsSheets("Output”).Cells(17, 2) = “Territory Name”
Range(“Test_Range”).row or .column will return the row/column that the named range is located in
Use meaningful variable names. Use at least one capital letter in variable names If they are typed correctly, VBA will capitalize them, making it easy to spot typos
CTRL + Space Brings up an auto complete menu that includes user defined functions and
variables after typing only a few letters
Turning off “Auto Syntax” If a line of code is unrecognized in VBA, you will get a message box alerting
you• This becomes an annoyance if you want to move away from the line of code before
you finish typing it To turn off: Tools Options Uncheck “Auto Syntax Check”
Use white space to separate logic blocks
Make sure to lower the “Macro Security” level to medium in Excel otherwise you will not be able to enable the use of macros In Excel: Tools Macro Security Medium
Open Database Connectivity (ODBC) and OLE DB is the underlying technology, application programming interface (API) that interfaces between our programs and the source of data, such as Access, SQL Server, Oracle, etc. Used in Windows C and C++
programming
ADO are ActiveX objects that provides easy access to the OLE DB and ODBC functionality. Used in Visual Basic and Java.
Microsoft Data Access Components (MDAC) ties it all together by packaging ADO with the necessary OLE DB providers
Connection object The Connection object sets up a link between your program and the data source. This
object contains all of the necessary configuration information and acts as a gateway for all of the other ADO objects.
Command object The Command object executes SQL strings, stored procedures, or action queries. Command objects may have an associated collection of Parameter objects that provide
additional information to the data source when executing the command.
Recordset object Recordset object creates and manages a collection of records. It contains navigational
methods to move to a particular record. Each Recordset object is composed of a number of Field objects that represent individual
columns in the Recordset. Each command execution results in a Recordset containing the results of the query.
Create connection objectDim objConn As ADODB.ConnectionSet objConn = New ADODB.ConnectionObjConn.Open =”DSN=myDSN;UID=master;PWD=slave”
Close a connectionobjConn.CloseSET objConn=Nothing
Connection String - designates data source name and tells which provider is being used. ODBC data source name: DSN = myDSN. This is used when connecting to SQL Server. Text string
Both Command and Connection objects have a method named Execute. Syntax: .Execute (RecordsAffcted, Parameters, Options) Give it an SQL command (as a parameter) and it creates a Recordset object.
The Recordset object contains the result of the SQL query. Set result=objCmd.Execute("SELECT * FROM Password")
Command time out: time (secs) ADO waits for command to be returned before aborting Example: objComm.CommandTimeout = 0. 0 means infinity.
Command type specifies the type of command object to be or being used, types are adCmdText: Evaluates CommandText as a textual definition of a command or
stored procedure call. adCmdTable: Evaluates CommandText as table name whose columns are
all returned by internally generated SQL query. adCmdStoredProc: Evaluates CommandText as a stored procedure name. adCmdUnknown: Default. The type of command in the CommandText
A RecordSet object holds a collection of records (from the database) and has some methods: EOF() : boolean that indicates there are no more records. MoveNext(): moves to the next record MovePrevious(): move to previous record MoveFirst(): move to the first record GetRows(): Fetches a block of rows into an array. Very efficient when retrieving
A cursor is what manages the set of records and the current location within the recordset, the latter being handled by the current record pointer. A good way to think about it is to imagine the cursor as a single row window
that can move up and down the recordset.
Cursor is very important as it determines what you can do with the recordset.
Cursor location: determine where the cursor lives. Certain data source, such as SQL Server, have a cursor service of their own,
whereas others, such as Access, don’t have a cursor service. ADO has its own cursor service. Use CursoLocation property:
• adUseServer – To let the data source manipulate the cursor• adUseClient – To let ADO maninuplate the cursor.
This is a simplified version of a real life application: We have a list of dinner program participants with DocID stored in table T_Participants.
We have the prescription information of all physicians including those program participants, stored in table T_Prescription.
For each participant, we would like to find a control among all non-participants who has the closest 24th month prescription as the participant and whose scripts are no more and less than 20 of that of this participant.
At the end, we will save all participants with their identified controls into T_matched table with two columns: ParticipantID, and NonParticipantID.
We use this example to illustrate two things: How you can save results back to the database. You should always try to separate the logic into a few blocks and then put each block
into a function/procedure. This will make the whole code much easier to read and understand.
• In this example, we split the main logic into three pieces: read data, find controls, and save data.• Can you see how long the main() function will be if we put all code into it only?
We only show two functions here. For the complete code illustration, please refer to accompanied “VBA Example” excel file.
By adding the picture toolbar (Right Click on the toolbar Click on “Picture”) you can select the “Crop” option This will allow you to crop off certain areas of the picture you paste
Resizing Pictures You can also right click on the picture and click on “Format Picture” The size tab will allow you to keep graphs and tables pasted from Excel the
PowerPoint has several features that will help maintain the consistency of the placement of objects on slides throughout the presentation
Centering an object on the slide In the lower left hand corner of PowerPoint, there is a “Draw” menu
• Draw “Align or Distribute” “Relative to Slide”• Draw “Align or Distribute” “Align Center” : This will center the object horizontally on the
page• Draw “Align or Distribute” “Align Middle” : This will center the object vertically on the page
If there are multiple objects to align on the page, “Drawing Guides” are more useful Right click on the slide: Click “Grid and Guides” and Check “Display Drawing Guides on
Screen”• This place one centered vertical and one centered horizontal line on the slides• These lines can be duplicated (Click on the line, hold “Ctrl” and drag the line to a new position• By aligning these with objects in your presentation, it will help to maintain consistency
By Holding “Ctrl” and using the arrow keys, you will have greater control over the movement of the picture on the slide