[Slides notes] Financial Modeling using VBA

本文详细介绍了Excel VBA的基础操作,包括初始化环境、宏录制与编辑、对象模型使用、变量与常量、基本运算符与语句、数组、子过程与函数、内置函数等,并通过实例展示了绝对引用与相对引用的运用,以及如何在单元格中赋值。同时提供了如何在项目浏览器窗口中查看和编辑代码的方法,以及如何添加和删除模块。此外,还涵盖了数据类型、作用域、常量、日期格式、字符串操作、数组操作、循环结构、注释编写、数组复制、函数与子过程定义、错误处理等内容。

Initialization:
1. Left click Office Button, Left click Excel Options. Check Show Developer tab in the Ribbon. Left click OK.
2. Select Developer tab. Left click on Macro Security.
3. Check Enable all macros and Trust access to the the VBA project model. Left click OK.

Macro Recorder

Press Alt + F8 to look over macro, to edit or run it.

  • Record your actions in VBA
    • Under the Developer Tab, left click on Record Macro. Name the record and click OK.
    • Begin record the actions in VBA and left click the mouse button on Stop Recording
  • Assign marco to button
    • Select Developer tab, left click on Insert. And select Button
    • Left click mouse button anywhere, and draw a button.
    • In the Assign Macro dialogue, select a function and click OK.
    • Name the button.
  • Modifying macro code
    Select the cell and assign the value.
    Or assign the value directly.
    • Absolute and Relative Reference

    ''''Absolute Reference
    Sub EnterValues()
    '
    ' EnterValues Macro
    ' Macro recorded 7/21/2008 by CD Shum
    '
        Range("B40").Select
        ActiveCell.FormulaR1C1 = "ABC"
        Range("B41").Select
        ActiveCell.FormulaR1C1 = "DEFG"
        Range("B42").Select
        ActiveCell.FormulaR1C1 = "100"
        Range("B43").Select
        ActiveCell.FormulaR1C1 = "200"
        Range("B44").Select
        ActiveCell.FormulaR1C1 = "=R[-1]C"
        Range("B45").Select
    End Sub
    ''''Relative Reference
    Sub EnterValuesRelative()
    '
    ' EnterValuesRelative Macro
    ' Macro recorded 7/21/2008 by CD Shum
    '
        ActiveCell.Offset(0, 0).Range("A1").Select
        ActiveCell.FormulaR1C1 = "ABC"
        ActiveCell.Offset(1, 0).Range("A1").Select
        ActiveCell.FormulaR1C1 = "DEFG"
        ActiveCell.Offset(1, 0).Range("A1").Select
        ActiveCell.FormulaR1C1 = "100"
        ActiveCell.Offset(1, 0).Range("A1").Select
        ActiveCell.FormulaR1C1 = "200"
        ActiveCell.Offset(1, 0).Range("A1").Select
        ActiveCell.FormulaR1C1 = "=R[-1]C"
        ActiveCell.Offset(1, 0).Range("A1").Select
    End Sub

    Object

    Object ModelExample
    PropertiesWorksheets(“Object”).ActiveCell**.Font.Size**
    PropertiesWorksheets(“Object”).Range(“ClearContents”).Value
    MethodWorksheets(“Object”).Range(“ClearContents”).ClearContents
    MethodWorkbooks**.Open(“excel_intro_ans.xls”)**
    MethodWorksheets(“Macro Recorder”).Active
    HierarchyApplication.Workbooks(“vba_intro_ans.xls”).Sheets(“Object”).Range(“YellowCells”)

    Help:
    Press Alt + F11 to go to Microsoft Visual Basic.
    Press F1 to go to Microsoft Visual Basic Help.
    Under the Excel Help, left click Excel Object Model Reference.


    Basics

    • Invoke Visual Basic Editor
      Press Alt + F11 or under Developer tab, left click Visual Basic.
    • Project Explorer Window
      If not visible, select View–> Project Explorer.
      Code in Microsoft Excel Objects (e.g. Sheet1) or Modules (e.g. Module 1)
      Double click left mouse button on Module 1 to view code.
      To insert a module, select Insert –> Module.
      To remove a module, select the module, right click and select Remove Module.
    • Entering Code
      In the Project Explorer Window, double click left mouse on a sheet to view code.
      Each Sub and End Sub is a procedure.
    • Getting help
      MsgBox is a VBA built-in function. To get help on MsgBox, in the Code Window, right click mouse button on MsgBox. Select Definition. Left click mouse button on ?.
    • Adding Comment
      Text after (‘) is a comment.
    • Line Continuation
      A statement is on a line.
      Continue a statement in the next line by putting a space followed by an underscore(_) at the end.

    Variables

    • Variables: Named storage.
    • Naming Variables: Case insensitive. E.g., “aBC” is the same as “abc”.
      Cannot use space( ), period(.), exclamation mark(!) or @, &, $, and #. Also, cannot use key words reversed by VBA (e.g., Dim, Integer, Sub).
      Best Practice: Variable names should be descriptive(e.g. SpotPrice, StrikePrice)
    • Data Types:
    TypeDescription
    Boolean(True or False) Converted from numeric types (0 to False; others to True)
    Byte(0 - 255)
    Currency@(15 digits to the left and 4 digits to the right of decimal point) 64-bit
    Date(date literals #9 Aug 2008#)(e.g., dateV = #9 Aug 2008#)
    Single(floating point) 32-bit
    Double #(floating point) 64-bit
    Integer %(-32,768 to 32,767) 16-bit
    Long &(-2,147,483,648 to 2,147,483,647) 32-bit
    String $(fixed length 64K characters; variable-length 2^31 characters)
    Object(addresses to objects)
    Variant(any kind of data except fixed-length String)
    • Scope:
      • Procedure-Level: Declared within procedure using Dim. Available only within procedure of declaration. Variables not explicitly declared are treated as procedure-level variables.
      • Static: Declared within procedure using Static. Available as long as code (project) is running (even after procedure has ended).
      • Module-Level: Declared before 1st procedure of module using Dim or Private. Available as long as code (project) is running.
      • Project-Level: Declared using Public at the beginning (before 1st procedure) of one of the modules. Available to all procedures as long as code (project) is running.

    Constants

    • Date Constants
      date constants
    • Color Constants
      color constants
    • MsgBox Constants
      msgbox constants1
      msgbox constants2
    • VarType Constants
      varType constants

    Operators

    • Common Operators
      Common Operators
    • Comparison Operators
      comp operators
      other operators

    Statements

    • If … Then … Else
    If condition Then [statements][Else elsestatements]

    or

    If condition Then
        [statements]
    [ElseIf condition Then
        [elseifstatements]...
    [Else
        [elsestatements]]
    End If
    • Select Case
    Select Case testexpression
        [Case expressionslist
            [statements]]...
        [Case Else
            [elsestatements]]
    End Select
    • For … Next
    For counter = start To end [Step step]
        [statements]
        [Exit For]
        [statements]
    Next[counter]
    • For Each … Next
    For Each element In group
        [statements]
        [Exit For]
        [statements]
    Next[element]
    • Do … Loop
    Do [{While | Until} condition]
        [statements]
        [Exit Do]
        [statements]
    Loop

    Or

    Do
        [statements]
        [Exit Do]
        [statements]
    Loop [{While | Until} condition]

    Array

    fixed-size array: known fixed storage
    dynamic array:dynamic storage, can be reallocated using ReDim or released using Erase

    • Dim
    Dim [Preserve] varname(subscripts) [As type][,varname(subscripts)[As type]]...

    e.g., fixed-size array Dim iFixedSizeArray(10) as Integer
    e.g., dynamic array Dim iDynamicArray() as Integer

    • ReDim:
    ReDim [Preserve] varname (subscripts) [As type][, varname(subscripts) [As type]]...

    Preserve: preserve data in an existing array, can resize only the last array dimension, can only change the upper bound.
    without Preserve: numeric variable is initialized to 0, variable-length string is initialized to zero-length string (“”), fix-length string is filled with zeros. Variant variable are initialized to Empty, object variable has special value Nothing.

    • Erase
      fixed-size: reinitialize, recover no memory
      dynamic: frees memory

    • Array Copy

      • Cannot assign to fixed-size array
      • Assign to dynamic OK:
      • Assign to Variant OK:
    Sub fixedArray()
        Dim iFA(10) As Integer   'initialized to 0
        Dim i As Integer
        For i = 0 To 10
            iFA(i) = i
        Next i
        'ReDim iFA(20)           'uncomment and compile to see error
        Erase iFA
        Dim fsA(5) As String * 5    'initialized to 0
        Dim b() As Byte
        b = fsA(0)
    End Sub
    Sub dynamicArray()
        Dim sDA() As String
        ReDim sDA(1, 1)         'initialized to ""
        sDA(0, 0) = "element(0,0)": sDA(0, 1) = "element(0,1)"
        sDA(1, 0) = "element(1,0)": sDA(1, 1) = "element(1,1)"
        ReDim Preserve sDA(1, 2)
        'ReDim Preserve sDA(2, 2) 'uncomment and run to see error
        ReDim sDA(2, 2)          'all reinitialized to ""
        Erase sDA                'release dynamic storage
    End Sub

    /// Do not use Variant often, since the complier can not find some type mistake by unknown types


    Sub & Function

    • Sub
    [Private | Public][Static] Sub name [(arglist)]
        [statements]
        [Exit Sub]
        [statements]
    End Sub

    001
    002
    003
    004

    • Function
    [Public | Private][Static] Function name [(arglist)][As type]
        [statements]
        [name = expression]
        [Exit Function]
        [statements]
        [name = expression]
    End Function    

    A sub is a procedure return nothing, a function return something with using [As type].


    Built-In Function

    In VBA, there are types of build-in function you can use. Press Alt + F11 to go to Microsoft Visual Baisc. In the standard toolbar, left click mouse button on Object Browser.
    built-in function

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值