XP Week 6 – ABC By Aurino Djamaris Bakrie School of Management.

Post on 27-Dec-2015

221 views 3 download

Transcript of XP Week 6 – ABC By Aurino Djamaris Bakrie School of Management.

XPXP

Week 6 – ABC

By Aurino DjamarisBakrie School of Management

XPXPError handling, Debugging and User Interface within Excel• Error handling Techniques• Debugging• creating dialog boxes, • userform basics, • using userform controls, and • implement some techniques and tricks, • using macro through user interface

XPXPError-Handling Techniques

• Identifying errors• Doing something about the errors that occur• Recovering from errors• Creating intentional errors (Yes, sometimes an

error can be a good thing.)

write code that avoids displaying Excel’s error messages as much as possible

XPXPExcel Error Messages • Excel responds with the message shown below, indicating that your code

generated a run-time error

Excel displays this error message when theProcedure attempts toCalculate the squareroot of a negative number.

XPXPError Handling• Anticipate this error and handle it. Example : Sub EnterSquareRoot ()

Error Handling 1

Error Handling 2

XPXPHandling Errors Another Way• adding an On Error statement to trap all errors and then checking to see

whether the InputBox was cancelled.

XPXPOn Error Problem?

Using an On Error statement in your VBA code causes Excel to bypass its built-in error handling and use your own error-handling code.

XPXPOn Error Statements

XPXPResuming on Error

XPXPExample: Resume after an error occurs

XPXPWhat Error and Err Number

Trap Error

Treat Error accordingly

XPXPAn Intentional Error

The Macro1 procedure (which must be in the same project as WorkbookOpen) calls the WorkbookOpen function and passes the workbook name (Prices.xlsx) as an argument.

XPXPBug Extermination Techniques• Defining a bug and why you should squash it• Recognizing types of program bugs you may

encounter• Using techniques for debugging your code• Using the VBA built-in debugging tools

XPXPThe bugs categories• Logic flaws in your code.• Incorrect context bugs• Extreme-case bugs• Wrong data type bugs• Wrong version bugs• Beyond-your-control bugs

XPXPIdentifying Bugs• An error message like this often means that your

VBA code contains a bug.

• The best debugging approach is thorough testing, under a variety of real-life conditions

XPXPDebugging TechniquesFour most common methods for debugging Excel VBA code:• Examining the code: taking a close look at your code• Inserting MsgBox functions at various locations in your code:

– MsgBox LoopIndex & “ “ & CellCount– MsgBox LoopIndex & vbNewLine & CellCount & vbNewLine & MyVal– MsgBox ActiveSheet.Name & “ “ & TypeName(ActiveSheet)

• Inserting Debug.Print statements– Debug.Print LoopIndex, CellCount, MyVal

• Using the Excel built-in debugging tools:– Excel includes a set of debugging tools that can help you correct problems

in your VBA code.

XPXPthe Debugger• set a breakpoint in your VBA code

XPXPUsing the Immediate window• display the VBE’s Immediate window pressing Ctrl+G.• for finding the current value of any variable in your program.

XPXPBug Reduction Tips• Use an Option Explicit statement at the beginning of your

modules.• Format your code with indentation. • Be careful with the On Error Resume Next statement. • Use lots of comments. Nothing is more frustrating than

revisiting code• Keep your Sub and Function procedures simple. • Use the macro recorder to help identify properties and

methods.• Understand Excel’s debugger.

XPXPVBA Programming Examples• Working with ranges• Changing Excel settings• Working with charts• Speeding up your VBA code

XPXPWorking with ranges• Copying a

range

• more efficiently

XPXPCopying a variable-sized range

or

XPXPSelecting to the end of a row or column

• use the CurrentRegion property to select an entire block of cells.

• End method takes one argument constants use:– xlUp– xlDown– xlToLeft– xlToRight

XPXPSelecting to the end of a row or column (cont)

• Selecting a row or column

• Moving a range

• Looping through a range efficiently

XPXPSkip Blanks examplesprocessing only the nonblank cells using the SpecialCells method.the selection’s subset that consists of cells with constants and the selection’s subset that consists of cells with formulas

XPXPPrompting for a cell valueuse VBA’s InputBox function to get a value from the user.

or

XPXPOther selection methods

Identifying a multiple selection

Determining the selection type

determine whether the user madea multiple selection

displays a message and exits the procedure if the currentselection is not a Range object:

XPXPChanging Excel Settings• Changing Boolean settings

• Changing non-Boolean settings

togglesthe calculation mode between manual and automatic

the Not operator to effectively toggle the page break display

XPXPWorking with Charts• Modifying the chart type

• Looping through the ChartObjects collection

XPXPWorking with Charts (cont)• Modifying chart properties

XPXPWorking with Charts (cont)• Applying chart formatting

XPXPVBA Speed Tips• Turning off screen updating

– Application.ScreenUpdating = False / True

• Turning off automatic calculation– Application.Calculation = xlCalculationManual / xlCalculationAutomatic

• Eliminating those pesky alert messages– Application.DisplayAlerts = False /True

• Simplifying object references– defining this object variable, then define the value rather than defining this

object variable and the value in single line

• Declaring variable types– use the data type that requires the smallest number of bytes yet can still

handle all the data assigned to it.

XPXPUsing the With-End With structure• Use

• Rather than

XPXPUSER INTERFACES• Simple Dialog Boxes• UserForm Basics• UserForm Controls• UserForm Techniques and Tricks• Accessing Your Macros Through the User

Interface

XPXPSimple Dialog Boxes• The MsgBox function• The InputBox function• The GetOpenFileName method• The GetSaveAsFileName method

XPXPMsgBox• MsgBox(prompt[, buttons][, title])

XPXPInputBox• InputBox(prompt[, title][, default])

XPXPGetOpenFileName• object.GetOpenFilen

ame([fileFilter], [filterIndex], [title], [buttonText], [multiSelect])

XPXPSelecting Multiple File

XPXPGetSaveAsFileName

• object.GetSaveAsFilename([initialFilename], [fileFilter],[filterIndex], [title], [buttonText])

The Excel GetSaveAsFilename method works just like the GetOpenFilename method, but it displays the Excel Save As dialog box rather than its Open dialog box. The GetSaveAsFilename method gets a path and filename from the user but doesn’t do anything with it.

XPXPGetting a folder name

allows the user to select a directory.

XPXPUserForm Basics• Creating UserForms1. Determine how the dialog box will be used 2. Press Alt+F11 to activate the VBE and insert a new UserForm object.3. Add controls to the UserForm.4. Use the Properties window to modify the properties for the controls or for

the UserForm itself.5. Write event-handler procedures for the controls (for example, a macro that

executes when the user clicks a button in the dialog box).6. Write a procedure (stored in a VBA module) that displays the dialog box to

the user.

XPXPInserting a new UserForm

• 1. Activate the VBE by pressing Alt+F11.• 2. Select the workbook in the Project window.• 3. Choose Insert UserForm. ➪

XPXPAdding controls to a UserForm

• You use the tools in the Toolbox to add controls to UserForm.

XPXPChanging properties for a UserForm control

• Properties for controls include the following:1. Name2. Width3. Height4. Value5. Caption

XPXPViewing the UserForm Code window

• Every UserForm object has a Code module that holds the VBA code (the event-handler procedures) executed when the user works with the dialog box. To view the Code module, press F7. The Code window is empty until you add some procedures. Press Shift+F7 to return to the dialog box.

XPXPDisplaying a UserForm• The macro that displays the dialog box must be in a VBA module

— not in the Code window for the UserForm.

XPXPUsing information from a UserForm• The VBE provides a name for each control you add to a UserForm.

The control’s name corresponds to its Name property. Use this name to refer to a particular control in your code.

XPXPA UserForm Example• Creating the UserForm1. Press Alt+F11 to activate the VBE.2. If multiple projects are in the Project window, select the

project that corresponds to the workbook you’re using.3. Choose Insert UserForm.➪4. Press F4 to display the Properties window.5. In the Properties window, change the dialog box’s Caption

property to Change Case.6. The dialog box is a bit too large, so you may want to click it and

use the handles to make it smaller.

XPXPAdding the CommandButtons1. Make sure that the toolbox is displayed. If it isn’t, choose View Toolbox.➪2. If the Properties window isn’t visible, press F4 to display it.3. In the toolbox, drag a CommandButton into the dialog box to create a button.4. Make sure that the CommandButton is selected. Then activate the Properties

window and change the following properties:

5. Add a second CommandButton object to the UserForm and change thefollowing properties:

6. Adjust the size and position of the controls so your dialog box looks something like Figure 16-5.

XPXPFigure 16-5

XPXPAdding the OptionButtons1. In the toolbox, click the Frame tool and drag in the dialog box.2. Use the Properties window to change the frame’s caption to Options. 3. In the Toolbox, click the OptionButton tool and drag in the dialog box

(within the Frame).4. Select the OptionButton and use the Properties window to change the

following properties:

5. Add another OptionButton and use the Properties window to change the following properties:

XPXPAdding the OptionButtons6. Add a third OptionButton and use the Properties window to change the

following properties:

7. Adjust the size and position of the OptionButtons, Frame, and dialog box.

XPXPAdding event-handler procedures1. Double-click the Cancel button.2. Insert the following statement inside the procedure (before

the End Sub statement):3. Press Shift+F7 to return to the UserForm.4. Double-click the OK button.5. Enter the following code inside the procedure:

XPXP

XPXPCreating a macro to display the dialog box

1. In the VBE window, choose Insert Module.➪2. Enter the following code:

XPXPMaking the macro available1. Activate the Excel window via Alt+F11.2. Choose Developer Code Macros or press Alt+F8.➪ ➪3. In the Macros dialog box, select the ChangeCase macro.4. Click the Options button.5. Enter an uppercase C for the Shortcut key.6. Enter a description of the macro in the Description field.7. Click OK.8. Click Cancel when you return to the Macro dialog box.

XPXPTesting the macro1. Activate a worksheet (any worksheet in any workbook).2. Select some cells that contain text.3. Press Ctrl+Shift+C.4. Make your choice and click OK.

XPXPUserForm Controls• Adding controls1. Click the Toolbox tool that corresponds to the control you want to add.2. Click in the UserForm.3. Drag the control into position.

XPXPIntroducing control properties

XPXP

XPXP

Changepropertiesby selectingfrom a dropdownlistof validpropertyvalues.

XPXPDialog Box Controls: The Details

• CheckBox control• Accelerator: A letter that lets the user change the value of the control by

using the keyboard. For example, if the accelerator is A, pressing Alt+A changes the value of the CheckBox control (from checked to unchecked, or from unchecked to checked).

• ControlSource: The address of a worksheet cell that’s linked to the CheckBox. The cell displays TRUE if the control is checked or FALSE if the control is not checked.

• Value: If True, the CheckBox has a check mark. If False, it does not have a check mark.

XPXPComboBox control

is a drop-downbox and displays only one item at a time

XPXPCommandButton control

XPXPOther controls• Frame control• Image control• Label control• ListBox control• MultiPage control• OptionButton control• RefEdit control• ScrollBar control• SpinButton control• TabStrip control• TextBox control• ToggleButton control

XPXPUserForm Techniques and Tricks

• Using Dialog Boxes• A UserForm Example

– Creating the dialog box– Writing code to display the

dialog box– Making the macro available– Trying out your dialog box– Adding event-handler

procedures– Validating the data– Now the dialog box works

• More UserForm Examples– A ListBox example

– Selecting a range– Using multiple sets of

OptionButtons– Using a SpinButton and a

TextBox– Using a UserForm as a progress

indicator– Creating a tabbed dialog box– Displaying a chart in a dialog

box

• A Dialog Box Checklist

See Chapter 18. UserForm Techniques and Tricks

XPXPAccessing Macros Through the User Interface

XPXPWorking with CommandBars

XPXPVBA Shortcut Menu Examples

XPXPAdd to shortcut menu

XPXPCreate a toolbar