microsoft office excel 2007 -- vba step by step

4
MICROSOFT OFFICE EXCEL 2007 VISUAL BASIC FOR APPLICATIONS STEP BY STEP -- Reed Jacobson ISBN: 9780735624023 Microsoft Press 2007 (384 pages) CONTENTS Chapter 1 Make a Macro Do Simple Tasks Chapter 2 Make a Macro Do Complex Tasks Chapter 3 Explore Workbooks and Worksheets Chapter 4 Explore Range Objects Chapter 5 Explore Data Objects Chapter 6 Explore Graphical Objects Chapter 7 Control Visual Basic Chapter 8 Extend Excel and Visual Basic Chapter 9 Launch Macros with Events Chapter 10 Use Dialog Box Controls on a Worksheet Chapter 11 Create a Custom Form Appendix A Complete Enterprise Information System Chapter 1 Make a Macro Do Simple Tasks Objective Record and run a macro. Understand and edit simple recorded macros. Run a macro by using a shortcut key. Manage macro security What is the Difference Between VBA and a Macro? -- VBA acts as a general-purpose language that is independent of the application whereas a macro is a computer program that gives automated instructions to the computer. VBA works with an object model. In an object model, each different part of the application-for example, a workbook, a range, or a point on a chart-becomes an object, and each object has its own list of functions. Objects are basically just a way of logically organizing the million of commands that are possible in Excel. This means that an Excel VBA macro can control not only Excel, but also any application that provides an object model. All Microsoft Office applications, and several other Microsoft and non-Microsoft applications, provide appropriate object models. Any language that supports Automation can control Excel. With a

Upload: proxydownload

Post on 29-Oct-2015

52 views

Category:

Documents


10 download

DESCRIPTION

MsExcel2007

TRANSCRIPT

Page 1: Microsoft Office Excel 2007 -- VBA Step by Step

MICROSOFT OFFICE EXCEL 2007 VISUAL BASIC FOR APPLICATIONS STEP BY STEP-- Reed Jacobson ISBN: 9780735624023 Microsoft Press 2007 (384 pages)

CONTENTSChapter 1 Make a Macro Do Simple Tasks Chapter 2 Make a Macro Do Complex Tasks Chapter 3 Explore Workbooks and Worksheets Chapter 4 Explore Range Objects Chapter 5 Explore Data Objects Chapter 6 Explore Graphical Objects Chapter 7 Control Visual Basic Chapter 8 Extend Excel and Visual Basic Chapter 9 Launch Macros with Events Chapter 10 Use Dialog Box Controls on a Worksheet Chapter 11 Create a Custom Form Appendix A Complete Enterprise Information System

Chapter 1 Make a Macro Do Simple Tasks Objective

Record and run a macro. Understand and edit simple recorded macros. Run a macro by using a shortcut key. Manage macro security

What is the Difference Between VBA and a Macro? -- VBA acts as a general-purpose language that is independent of the application whereas a macro is a computer program that gives automated instructions to the computer.

VBA works with an object model. In an object model, each different part of the application-for example, a workbook, a range, or a point on a chart-becomes an object, and each object has its own list of functions. Objects are basically just a way of logically organizing the million of commands that are possible in Excel. This means that an Excel VBA macro can control not only Excel, but also any application that provides an object model. All Microsoft Office applications, and several other Microsoft and non-Microsoft applications, provide appropriate object models. Any language that supports Automation can control Excel. With a simple translation layer, you can also talk to the Excel object model from Microsoft .NET applications written in C# or Microsoft Visual Basic .NET.

The MacroTIP--Excel uses many Ctrl key combinations as built-in shortcuts. For example, Ctrl+C is Copy and Ctrl+Z is Undo. If you assign one of these

shortcuts to your macro, pressing the shortcut key combination runs your macro rather than the built-in command. If you always use Ctrl+Shift key combinations when you assign shortcut keys to your macros, you’ll be less likely to override a built-in shortcut.

Sub FormatCurrency()' FormatCurrency Macro ' Selection.NumberFormat = "$#,##0" End Sub

A module is the place where the recorder stores macros.An apostrophe tells Visual Basic to ignore all subsequent text on the line. Comments appear in green to help you

distinguish them from statements. Everything in Visual Basic that is not a comment is a statement. A statement tells Visual Basic what to do.

The first statement in the macro begins with Sub, followed by the name of the macro. This statement tells Visual Basic to begin a new macro. The final statement of the macro is End Sub. This statement tells Visual Basic to come back to the surface.

TIP-- Macro-free workbooks happen to have the extension .xlsx, and macro-enabled workbooks have the extension .xlsmSub SideBarHeading()'' SideBarHeading Macro' Merge and Rotate cells Vertically '' Keyboard Shortcut: Ctrl+Shift+S' With Selection

Page 2: Microsoft Office Excel 2007 -- VBA Step by Step

.HorizontalAlignment = xlGeneral .VerticalAlignment = xlBottom .WrapText = False .Orientation = 90 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = True End With

End Sub

The group of statements from With to End With is called a With structure. Inside a ‘With structure’, you can put a dangling period in front of a property, and VBA just pretends that the object from the ‘With statement’ is there. A ‘With structure’ makes the code easier to read because you can tell instantly that all the properties relate to the same object-in this case.

You can make your macro easier to understand if you eliminate unnecessary property assignments. You can keep only the properties you need to change.

The simplified macro (ignoring the comment lines, which you can delete if you want) should look like this: Sub SideBarHeading() With Selection .Orientation = 90 .MergeCells = True End With End Sub

Manipulating Recorded Properties

Record a Macro to Remove Window Elements Sub CleanDisplay() ActiveWindow.DisplayGridlines = False ActiveWindow.DisplayHeadings = False Application.DisplayFormulaBar = FalseEnd Sub

You can read the first one as “Let ‘False’ be the Display Gridlines state of the active window.” This time you’re not changing the selected cells but rather the active window. The second statement also changes something about the active window, but the third one changes something called the Application. In each case, you’re changing the property of an object. A workbook window has different properties than a range of cells, and they have different properties than the application. The object is really justa way to group the properties.

Run the Macro from the Visual Basic Editor F5 from the Visual Basic editor is a fast way to run a macro while you’re testing it.Ctrl+Z three times to change all the True values back to FalseF8 steps through the macro, running one statement at a time

Use a Macro to Toggle the Value of a Property Sub ToggleCleanDisplay() ActiveWindow.DisplayGridlines = Not ActiveWindow.DisplayGridlines ActiveWindow.DisplayHeadings = Not ActiveWindow.DisplayHeadings Application.DisplayFormulaBar = Not Application.DisplayFormulaBar End Sub

The macro reads the old value of the property, changes it to the opposite with the keyword Not, and assigns the newly inverted value back to the property.

Eliminate Repeated Objects in a Recorded MacroWith ActiveWindow .DisplayGridlines = Not .DisplayGridlines .DisplayHeadings = Not .DisplayHeadings End WithWith Application .DisplayFormulaBar = Not.DisplayFormulaBar End With

Run a Macro from the Quick Access Toolbar A particularly nice feature of the Quick Access Toolbar is that you can add a button that appears only when the workbook containing the macro is active. This helps you avoid cluttering up the Quick Access Toolbar with unusable buttons.

Page 3: Microsoft Office Excel 2007 -- VBA Step by Step

Recording Methods in a Macro

Convert a Formula to a Value Sub ConvertToValues() Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False Application.CutCopyMode = False End Sub

The statement Selection.Copy has two words, separated by a period. A word followed by a period is probably an object, and that’s exactly what this is: a range of cells object. The word Copy, however, isn’t a property; it’s a method. That’s why it doesn’t have an equal sign after it. Remember that the object is really just a way of grouping available commands. You can copy a range of cells, but you can’t copy, say, a workbook window, so there’s no such thing as ActiveWindow.Copy.

The extra pieces of information you give to a method are called arguments.The four arguments you use with the PasteSpecial method correspond exactly to the four distinct parts of the Paste Special dialog box. Each argument even has a name that matches the caption in the dialog box: Paste, Operation, SkipBlanks, and Transpose. When you use an argument, you don’t actually have to include the argument name. This statement would function the same as Selection.PasteSpecial xlPasteValues, xlNone, False, False

The names just make it easier to read, so the macro recorder includes them. If you do use a name for an argument, you put a colon-equal sign (:=) between the argument name and its value. The colon-equal sign may include an equal sign, but it’s easy to tell them apart because the equal sign (used in a property assignment) always has a space on both sides.

Make a Long Statement More Readable When a statement in a macro gets to be longer than about 70 characters, the macro recorder inserts a space

and an underscore ( _) after a convenient word and continues the statement on the next line.Sub ConvertToValues() Selection.Copy Selection.PasteSpecial _ Paste:=xlValues, _ Operation:=xlNone, _ SkipBlanks:=False, _ Transpose:=False Application.CutCopyMode = False End Sub

Both properties and methods are separated from objects by periods, and both allow you to carry out actions. However, you assign a value to a property to carry out the action, whereas you simply execute a method, sometimes giving it arguments along the way.

Key Points The easiest way to start and stop recording macros is by using the small button in the status bar. To review or run macros, use the Macros button on the

View tab. Dock, undock, hide and show windows freely in the Visual Basic editor. It’s your working environment-make it work for you. When you have macros that relate to a single workbook, assign them to the Quick Access Toolbar for just that workbook. You might want to be more

judicious about which macros you assign to the global Quick Access Toolbar. Don’t be afraid to change what the macro recorder created-if you save a backup copy of the original, you can always restore it later. Delete unnecessary

statement and property assignments. This will make your macro much easier to understand the next time you use it. Take advantage of the new security features to keep your computer-and your company’s network-safe. Be very careful which folders and publishers you

trust. If you receive a macro-enabled workbook from someone else-whether you trust them or not-open it with macros disabled and inspect the macros before you put the workbook into a trusted location.