vba & excel

23
VBA & Excel Barry L. Nelson IEMS 465 Fall Quarter 2003

Upload: isabel

Post on 01-Oct-2015

261 views

Category:

Documents


15 download

DESCRIPTION

Excel programming

TRANSCRIPT

VBA & Excel

VBA & ExcelBarry L. NelsonIEMS 465Fall Quarter 2003VBAIs a significant subset of the stand-alone Visual Basic programming languageIt is integrated into Microsoft Office applications (and others, like Arena)It is the macro language of ExcelYou can addForms for dialog boxes with userClasses for object definitionsModules containing procedures

2Accessing VBA in ExcelTools Macros Visual Basic EditorEnter VBA through the navigation buttons in the top toolbars

VBA Design ModeVisual Basic EditorDesign mode is the time during which no code from the project is running and events from Excel or project will not execute. You can leave design mode by executing a macro or using the Immediate window.3VB Edit Window

Project ExplorerProperty InspectorCode WindowEdit Window Options4VariablesDeclare by DimBetter to use Data Types:Dim amount As DoubleDim year As IntegerDim name As StringOther data types: Boolean, Byte, Currency, DateDefault (no type) is Variant5Variable(contd.)% - integer& - long integer! - single# - double@ currency$ - stringanIntegerValue% =3, aString$ = "hallo"Can modify with scope (outside procedure)Private I As IntegerPublic billsPaid As CurrencyMake values permanentStatic yourName As StringMultiple variablesPrivate test, amount, J As Integer6Constants[Public|Private] Const constantName [As type] = expression

Public Const PI = 3.1, NumPLANETS = 9Const PI2 = PI * 2Const RELEASE = #1/1/99/#7Control StructuresDecisionIf anyDate < Now Then anyDate = Now

If anyDate < Now ThenanyDate = NowEnd If

If Then Else8Decisions(contd.)If Index = 0 ThenCopyActiveControlClearActiveControlElse If Index = 1 ThenCopyActiveControlElse If Index = 2 ThenClearActiveControlElsePasteActive ControlEnd If9Decisions(contd.)Select Case IndexCase 0CopyActiveControlClearActiveControlCase 1CopyActiveControlCase 2ClearActiveControlCase 3PasteActive ControlCase ElsefrmFind.ShowEnd Select10Loops/IterationsDo LoopDo While conditionstatementsLoop

DostatementsLoop While condition11Loops(contd.)For NextFor counter = start To end [Step increment]statements Next counterFor Each NextFor Each element In groupstatementsNext element

12Exiting Control StructuresFor counter = start To end [Step increment][statement block][Exit For][statement block]Next [counter [, counter][, ]]

Do [ {While|Until} condition][statement block][Exit Do][statement block]Loop13Exiting(contd.)Can also exit from a procedure:

Exit Sub14Code ModulesExcel Objects (ThisWorkbook, Sheet#)ModulesTypically we put our code hereA Module is a collection of Subs and FunctionsInsert ModuleClass ModulesUser Forms15ProceduresSub (routines)no value returnedCalled without parenthesismySub param1, param2Called with parenthesisCall mySub(param1, param2)Functionsvalue returnedassign return value to function name16Arguments for ProceduresPass by Reference (default)sub stuff(item As String) or sub stuff(ByRef item As String)stuff(car)Pass by Value (must be declared)sub stuff(ByVal item As String)Note that arguments must be formally declared (as must the return type of functions)17Some Useful CodeThe following are some pieces of code that are useful for doing VBA with Excel.See the code on the course web site for other examples.Finding/Creating a Sheet Dim found As Boolean Dim sheetNext As Worksheet ' Set up mySheet sheet for output found = False For Each sheetNext In Worksheets If sheetNext.Name = mySheet" Then found = True Exit For End If Next sheetNext If found = True Then Worksheets(mySheet").Select ActiveSheet.UsedRange.Clear Else Worksheets.Add ActiveSheet.Name = mySheet" End If Writing to a SheetPut the absolute value of the variable Fudge in row 2, column 20 of the Sheet named mySheet.Worksheets(mySheet).Cells(2,20) = VBA.Abs(Fudge)Use an Excel FunctionVBA has a limited number of built-in functionsYou can access any Excel worksheet function.This example uses the Excel Max functionW = WorksheetFunction.Max(0, W + S - a)Running the CodePerhaps the easiest way to run the code is to place your cursor in the module you want to run and press the Run Sub/UserForm button.Your modules will as appear as Macros that can be run from Excel under

Tools Macros MacrosFinishing UpExplore what is available in the IEMS 465 codeExercise: Write a Sub that inserts a worksheet named Count into the Workbook, then writes the numbers 1,2,,10 in the first row, the first ten columns. Use a loop to do this.