24
MgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants, Using Excel Functions in VBA, String

Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

Embed Size (px)

Citation preview

Page 1: Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

MgtOp 556—Advanced Business Modeling

Professor Munson

Topic 1

VBA Programming in Excel forDecision Support Systems

(Set 2—VBA Constants, Using Excel Functions in VBA, String Functions, “With”

Construction, and Working with Ranges)

“The majority of operations in Excel are range operations.”

Albright, S. Christian, VBA for Modelers, 5th Ed., Cengage Learning, 2016, p. 89

Page 2: Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

Built-In Constants in VBA

Arrow KeysxlDown, xlUp, xlToRight, and xlToLeft

ColorsvbBlack, vbBlue, vbCyan, vbGreen, vbMagenta, vbRed , vbWhite, and vbYellow

Horizontal AlignmentxlRight, xlLeft, and xlCenter

Message Box Icons vbInformation vbExclamation vbQuestion vbCritical

Page 3: Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

Using Excel Functions in VBA

You can use certain regular Excel functions in VBA code (not including the natural log, square root, random number, and IF) by preceding the function with:

WorksheetFunction.

As soon as you type the last period, a list of most Excel functions appears from which you can select. Examples

WorksheetFunction.MAX(Range(“A1:E1”))WorksheetFunction.SUM(Range(“A1:E1”))WorksheetFunction.AVERAGE(Range(“A1:E5”))WorksheetFunction.FLOOR(Range(“A2”),1)WorksheetFunction.RANDBETWEEN(1,6)

The IF Function in VBAThe IIf function in VBA uses the same syntax as the IF function in Excel (but ranges must be specified with VBA syntax such as )

12

A B C D E6 4 2 8 10

74.8

Page 4: Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

String Functions

Left(string, n)—returns the first n characters of string

Example: Left(“Mr. Spock”, 5)Result = “Mr. S”

Right(string, n)—returns the last n characters of string

Example: Right(“Vulcans Rule”, 4)Result = “Rule”

Mid(string, n1, n2)—starting a character n1 of string, returns the first n2 characters

Example: Mid(“Amok Time makes Vulcans crazy.”, 6, 18)

Result = “Time makes Vulcans”

Omitting n2 returns the rest of the string:Mid(“Amok Time makes Vulcans crazy.”, 6)

Result = “Time makes Vulcans crazy.”

Len(string)—returns the number of characters in string(spaces count)

Example:Len(“Captain Picard rocks!”)

Result = 21

Page 5: Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

Referencing Worksheets

Can refer to the “code names” of worksheets (and chart sheets).

Every worksheet has two “name” properties:(1) Name—the name shown on the sheet tab(2) CodeName—the name used by VBA

Set the CodeName using the “(Name)” property in the worksheet dialog box.

The following sheet has been named “Calculations” by the user (that shows up in the worksheet tab within Excel), while it has been given the CodeName “wsCalcs”.

Then you can refer to Cell B6 of “Calculations” as:

wsCalcs.Range(“B6”)

Page 6: Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

Properties of Ranges

Address: returns the address of a range as a stringEx: Range(“B3:F7”).Address returns “B3:F7”

Cells: refers to a specific cell in a rangeEx:Range(“B3:F7”).Cells(2,3) references cell D4

Range(“B3:B10”).Cells(4) references cell B6Range(“B3:F3”).Cells(4) references cell E3

Column: returns the number of the 1st column in the range

Ex:Range(“B3:F7”).Column returns 2Range(“D3:F7”).Column returns 4

CurrentRegion: references the smallest rectangle

surrounded by blank rows and columns that contains the range

Ex:

Range(“A4:A5”).CurrentRegion references A3:D6Range(“A10:C10”).CurrentRegion references A8:C11

12345678910111213

A B C D E

Item Quantity CostRice 3000 $200Beans 5000 $300 Note: bags weigh 5 pounds

Total 8000 $500

Item Quantity CostPeas 2000 $100Bananas 1000 $400

Total 3000 $500

Page 7: Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

1234

A B304070

1234

A B304070

EntireColumn: references the entire columns in the range (like clicking on the column labels)

Ex: Range(“B3:F7”).EntireColumn references columns B through F

EntireRow: references the entire rows in the range (like clicking on the row labels)

Ex: Range(“B3:F7”).EntireRow references rows 3 through 7

Font: references the font of the range—used to assign font properties

Ex: Range(“C4”).Font.Bold = True turns on bold Range(“C4”).Font.Italic = False turns off italics Range(“C4”).Font.Underline = True underlinesRange(“C4”).Font.Strikethrough = True applies strikethroughRange(“C4”).Font.Name = “Arial” assigns arial fontRange(“C4”).Font.Size = 12 assigns 12-point fontRange(“C4”).Font.Subscript = True converts to subscriptRange(“C4”).Font.Superscript = False removes superscriptRange(“C4”).Font.Color = vbBlue assigns blue fontRange(“C4”).Font.ColorIndex = 5 assigns blue font

Formula: returns the formula in the cell as a stringEx:

Range(“A3”).Formula returns “=A1+A2”

FormulaR1C1: returns the formula in the cell as a string in R1C1 notation

Ex:

Range(“A3”).FormulaR1C1 returns “=R[-2]C+R[-1]C”

Page 8: Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

HorizontalAlignment: horizontal alignment of cells in the range

Ex: Range(“B3:F7”).HorizontalAlignment = xlLeft left-justifiesRange(“B3:F7”).HorizontalAlignment = xlCenter centersRange(“B3”).HorizontalAlignment = xlRight right-justifies

Interior: references the interior of cells in the rangeEx: Range(“B3:F7”).Interior.Color = vbYellow colors cells yellow

Range(“B3:F7”).Interior.Color = RGB(255,0,0) colors cells redTo identify RGB colors in Excel, right click a cell, then:

Format Cells…Fill:More Colors…Custom

Name: creates a range nameEx: Range(“B3:F7”).Name = “Data” assigns the name “Data”

NumberFormat: specifies the number format for cells in the range

Ex: Range(“A2”).NumberFormat = “#,##0.00” formats as “, w/2 dec.”Common FormatsComma separator with 2 decimal places: “#,##0.00” Ex: 12,345.67Comma separator with 0 decimal places: “#,##0” Ex: 12,346Currency (and comma) w/ 2 decimal places: “$#,##0.00” Ex: $12,345.67Percentage with 2 decimal places: “0.00%” Ex: 96.45%

Handling negative valuesThe default displays a negative value in black preceded by a minus sign

Comma with 2 decimal places for other three negative formatsRed: “#,##0.00_);[Red]#,##0.00” Black with parenthesis: “#,##0.00_);(#,##0.00)” Red with parenthesis: “#,##0.00_);[Red](#,##0.00)”

Offset: provides a relative reference to a cellEx:Range(“B2”).Offset(3,4) refers to cell F5

Range(“B2”).Offset(0,3) refers to cell E2Range(“B2”).Offset(-1,0) refers to cell B1

Page 9: Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

1234

A BJanuary 2000February 1000March 5000

Total =SUM(B1:B3)

Row: returns the number of the 1st row in the rangeEx:Range(“B3:F7”).Row returns 3

Range(“D5:F7”).Row returns 5

Value: returns the value of the cellEx:

Range(“A2”).Value returns “February”Range(“B3”).Value returns 5000Range(“B4”).Value returns 8000

“With” ConstructionGreat shortcut for setting more than one propertyMust be accompanied by “End With”Try to indent for readabilityExampleWorksheets(“Sheet1”).Range(“D2”).Value = 452Worksheets(“Sheet1”).Range(“D2”).HorizontalAlignment = xlRightWorksheets(“Sheet1”).Range(“D2”).Font.Italic = TrueWorksheets(“Sheet1”).Range(“D2”).Font.Size = 16

Can be rewritten as:With Worksheets(“Sheet1”).Range(“D2”)

.Value = 452

.HorizontalAlignment = xlRightWith .Font

.Italic = True

.Size = 16End With

End With

Page 10: Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

Methods of Ranges

Clear: deletes everything—values and formattingEx: Range(“B3:F7”).Clear applies “clear all” to the range

ClearContents: deletes values but retains formatting

Ex: Range(“B3”).ClearContents applies “clear contents”

Copy: copies the rangeEx: Range(“B3:C5”).Copy Range(“F1”) copies B3:C5 to F1:G3

Range(“B3:C5”).Copy copies to the clipboard

PasteSpecial: applies “Paste Special” from the clipboard (from something previously copied)

Ex:Range(“G1”).PasteSpecial _ Paste:=xlPasteAll Paste:=xlPasteAllExceptBorders Paste:= xlPasteColumnWidthsPaste:=xlPasteCommentsPaste:=xlPasteFormatsPaste:=xlPasteFormulasPaste:=xlPasteFormulasAndNumberFormatsPaste:=xlPasteValidationPaste:=xlPasteValuesPaste:=xlPasteValuesAndNumberFormats

Select: selects the range (also for cursor movement)Ex: Range(“B3:G7”).Select selects (highlights) the range

Range(“V3”).Select moves the cursor to cell V3Range(“A9”).End(xlUp).Select <End><Up Arrow> from cell A9

Page 11: Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

123456

C D EName Exam Score GradeJohnny 78 C+Suzy 91 A-Sweetie 95 ACutie 91 A-Studley 73 C

123456

C D EName Exam Score GradeStudley 73 CJohnny 78 C+Suzy 91 A-Cutie 91 A-Sweetie 95 A

123456

C D EStudley 73 CJohnny 78 C+Suzy 91 A-Cutie 91 A-Sweetie 95 AName Exam Score Grade

123456

C D EName Exam Score GradeSweetie 95 ACutie 91 A-Suzy 91 A-Johnny 78 C+Studley 73 C

Sort: sorts the rangeEx:

Range(“C1:E6”).Sort Key1:=Range(“D1”), _ Order1:=xlAscending, Header:=xlYes

Range(“C1:E6”).Sort Key1:=Range(“D1”), _ Order1:=xlDecending, Key2:=Range(“C1”), _ Order2:=xlAscending, Header:=xlYes

Range(“C1:E6”).Sort Key1:=Range(“D1”), _ Order1:=xlAscending, Header:=xlNo

Page 12: Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

Specifying Ranges with VBA

1. Use an AddressEx: Range(“N1”) or Range(“B6:AX123”)

2. Use a Range Name (that has been previously defined in the worksheet)

Ex: Range(“Profit”)

3. Use a Range Object VariableEx: Dim profitRange As Range

Set profitRange = Range(“A1:C5”)profitRange.Font.Size = 15

4. Use the Cells PropertyEx: Range(“B3:G7”).Cells(1,2) refers to C3

5. Use the Offset PropertyEx: Range(“C6”).Offset(-3,2) refers to E3

6. Use Top Left and Bottom Right Arguments (only useful in combination with offsetting)

Ex: With Range(“A1”)Range(.Offset(2,1), .Offset(4, 3)).Select

End With this selects the range B3:D5

7. Use the End Property (works for variable range sizes)

Ex: With Range(“A1”)Range(.Offset(0,0), .End(xlDown).End(xlToRight)).Select

End With

Page 13: Dec S 340—Operations Management · Web viewMgtOp 556—Advanced Business Modeling Professor Munson Topic 1 VBA Programming in Excel for Decision Support Systems (Set 2—VBA Constants,

Section 6.5—Examples of Ranges with VBA

Example 6.1—Using AddressesMsgBox .Range(“A2:A19”).Address displays $A$2:$A$19 in a

message box

Example 6.2—Creating and Deleting Range Names.Names.Add Name:=“ScoreNames”, RefersTo:=.Range(“B1:F1”).Names(“ScoreNames”).Delete

Example 6.6—Using the End Property and the Offset PropertyWith a1

nScores = Range(.Offset(0,1),.End(xlToRight)).Columns.CountnEmployees = Range(.Offset(1, 0), .End(xlDown)).Rows.Count

Example 6.8—Referring to Rows and Columns.Rows(12) refers to the 12th row of a range.Columns(4).EntireColumn refers to the entire column

corresponding to the 4th column in the range (in this case D).Rows(“4:5”) refers to rows 4 and 5 of a range.Columns(“E:F”) refers to columns E and F of a range

Example 6.9—Formatting Cells in a Range.Range(“ScoreNames”).EntireColumn.AutoFit

Example 6.11—Referring to Other Range ObjectsDim a1 As Range, a21 as Range, h1 as RangeSet a1 = wsData.Range(“A1”)Set a21 = wsData.Range(“A21”)Set h1 = wsData.Range(“H1”)Dim UnionRange As RangeSet UnionRange = Union(a1.CurrentRegion, a21, h1) for noncontiguous ranges