0% found this document useful (0 votes)
14 views56 pages

Lec03 IE212 Objects S20

This document covers the manipulation of Excel objects using VBA, focusing on objects, properties, and methods. Key topics include the Range object, formatting options, debugging techniques, and the Application object. In-class exercises are provided to reinforce learning through practical application of the concepts discussed.

Uploaded by

Gabe Winter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views56 pages

Lec03 IE212 Objects S20

This document covers the manipulation of Excel objects using VBA, focusing on objects, properties, and methods. Key topics include the Range object, formatting options, debugging techniques, and the Application object. In-class exercises are provided to reinforce learning through practical application of the concepts discussed.

Uploaded by

Gabe Winter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

IE 212: Computational Methods for

Industrial Engineering

Lecture Notes #3:


Manipulating Excel Objects
Objects, Properties, and Methods

v In this module, various properties and methods for


commonly manipulated objects will be demonstrated
– Range From tutorial:
– Application What is the definition of a property?
Physical characteristics of objects that can be
– Workbook measured or quantified
– Worksheet What is the definition of a method?
Actions that can be performed by objects or on
objects
v The following aspects of programming in VBA will also be
discussed
– The With…End construct
– Cell naming and referencing
– Searching for new topics
– Debugging

2
Objects, Properties, and Methods (cont.)
v VBA code can be used to manipulate Excel objects to more
advanced degree than using just Excel functionality

v Knowing how to find object properties and methods with the


Object Browser and VBE tools is fundamental

3
Objects, Properties, and Methods (cont.)

v You can open the Object Browser from the View menu, by
clicking the Object Browser button on the main toolbar, or by
hitting F2.

4
Module Outline
v Topic overview (next slide)
v How to find new information
v Debugging introduction
v Topics
– Introduction on slides MAY NOT be covered in entirety during lecture.
– Material on slides is your responsibility to review
– In class exercises go through examples of topics on slides
– Some example code will be provided on Canvas and will be reviewed
in class

5
Overview of what
will be covered in
Lecture regarding
objects,
properties,
methods

6
Looking up new topics

v https://msdn.microsoft.com/en-us/library/office/ff840646.aspx
v Use Microsoft help if possible. It gives you syntax and
examples

7
Debugging
v Debugging tools

– To use now:
§ Stops or Breakpoints (F9)
To run until the breakpoint
§ Step into (F8)
To go line by line through code

– To use later:
§ Watch Window
§ Immediate Window

8
The Range Object
v The Range object is arguably the most used object in Excel
VBA
– A Range object can be a single cell, a rectangular block of cells, or
the union of many rectangular blocks (i.e., a non-continuous range)

v The Range object has several properties and methods, e.g.,


– Properties
§ Color
§ Border
§ Values
§ Font
– Methods
§ Clearing
§ Copy
§ PasteSpecial
9
Range – Color Format
v The Interior property is used to change the color of the
cell(s) within a range

v There are a few sub properties that can be used


– ColorIndex
– Color
– Pattern

10
Range – Color Format (cont.)
v ColorIndex property
– Value = numerical color index

Do online search for vba


excel msdn colorindex and
show what you get
compared to this slide.
Discuss how to get info
from it.

11
Range – Color Format (cont.)
v Color property
– Value = VB Constant or RGB Function

xlColorIndexNone works with this property!!

12
Range – Color Format (cont.)
v Color property
– Value = VB Constant or RGB Function

xlColorIndexNone works with this property!!


13
Range – Color Format (cont.)
v Pattern property
– Value = XL Constant

14
Range – Color Format (cont.)
Walk the students through the process of inserting a module.
v In-Class Exercise Also, remind them not to add code inside any of the Sheet objects

– Open file “Objects.xlsx”


– Save this file as “Objects.xlsm”
– Change the range “A1:F12” in Sheet1 so that the interior color is
BLUE, as shown in the figure below
§ Use all the properties just explained

– Also experiment with the property Pattern


§ Apply xlPatternGray50 and xlPatternSolid to the same cell range

15
Range – Border Format
v There is one main property and one main method to format
the border of a range

v The Borders property has several sub properties


– LineStyle
§ Value = xlDashed, xlSolid, …
§ Ex: Range(“A1:B2”).Borders.LineStyle= xlSolid
– Weight
§ Value = xlThick, xlThin, …
§ Ex: Range(“A1:B2”).Borders.Weight = xlThin
– Color
§ Value = VB Constant, RGB Function
§ Ex: Range(“A1:B2”).Borders.Color = vbBlue - or -
§ Ex: Range(“A1:B2”).Borders.Color = RGB(0, 0, 255)

16
Range – Border Format (cont.)
v The Borders property can also use XL Constants to control
specific borders
– Of an individual cell
§ xlEdgeTop, xlEdgeLeft, …
– Of a range of cells
§ xlInsideHorizontal, xlInsideVertical, …
– Ex: Range(“A1”).Borders(xlEdgeBottom).Weight = xlThin

17
Range – Border Format (cont.)
v Values for sub properties LineStyle and Weight

18
Range – Border Format (cont.)
v The BorderAround method has several possible arguments
– LineSytle:= xlDash, xlSolid, …
– Weight:= xlThick, xlThin, …
– Color:= VB Constant, RGB Function

v Notice that a combination of a colon and an equal sign are


used to define the argument of the method (:=)
– This is different than the values of properties that are set using just an
equal sign (= )

Range("A1:F12").BorderAround
LineStyle:=xlContinuous, Weight:=xlThick, Color:=vbBlack

19
Range – Border Format (cont.)
v In-Class Exercise
– Use the Excel file “Objects.xlsm” created previously
– Change the borders of the range “A1:F12” in Sheet2 so that it looks
like the figure shown below
§ Use both the Borders property and the BorderAround method

20
Range – Values
v The Value property is used in VBA to assign values to
ranges

v The value of a cell or a group of cells can be


– Text
– Numerical
– Formula
– Reference
– Variable

21
Range – Values (cont.)
v In-Class Exercise
– Write VBA code to enter several different values into Sheet3, as
shown below
§ Add Sheet3 to your workbook, if necessary

22
Range – Font Format
v The Font property is used in Excel VBA to format fonts of
ranges
v There are several sub properties to use with the Font
property
– Bold
§ Value = True or False
– Size
§ Value = number
– Color
§ Value = VB Constant, RGB Function
– ColorIndex
§ Value = number
– FontStyle
§ Value = “style”

23
Range – Font Format (cont.)
v In-Class Exercise
– Write VBA code to format the font of the values you entered in
Sheet3 so that the look as shown in the figure below

24
Range – Clearing Contents
v There are three methods commonly used to clear a range of
cells
– Clear
§ Clears everything
– ClearContents
§ Only clears values or formulas
– ClearFormats
§ Only clears formats

v It is important to know which method is most appropriate for


your worksheet

25
Range – Clearing Contents (cont.)
v In Class Exercise
– Write VBA code to produce the effects shown below in Sheet3

26
The Application Object
v The Application object is useful when executing VBA code
that copies and pastes large amounts of data
v This object has two main properties
– ScreenUpdating
§ Value = True or False
– CutCopyMode
§ Value = True or False

v There is also one main method


– Wait
§ Arguments = Now, TimeValue

27
The Application Object (cont.)
v The ScreenUpdating property
– Helps the VBA code run more efficiently since the Excel screen does
not need to be updated after every action in the code
§ Eliminates the flickering of the screen

v The CutCopyMode property


– Prevents a flashing box from remaining around the range which has
been copied after a macro has been executed

Range(””).select
Range(“”).copy

Application.cutcopymode = False (remove the dotted line)


Range(“).paste

28
The Application Object (cont.)
v In Class Exercise
– Insert a new worksheet into workbook “Objects.xlsm”
§ This will be Sheet4

v Enter the values shown below

v Write VBA code to understand the effect of the properties


CutCopyMode and ScreenUpdating
29
The Wait Method
v The Wait method is used frequently when Excel is used to
perform simulations

v Wait pauses the macro while it is being run until a specified


time is reached
– The Now argument
§ Calculates the current time
– The TimeValue argument
§ Gives an integer-valued time amount to add to the current time

v The macro will play again once Now plus TimeValue time is
reached
Application.Wait (Now + TimeValue("0:00:10"))

30
The Wait Method (cont.)
v In Class Exercise
– Use the Wait method to obtain the results shown below in Sheet4

Wait 5 seconds: show yellow box, wait 3 seconds: copy paste, change font,
show blue box

31
The With Construct
v The With construct is used to set several properties of one
object in an enclosed statement

v For example, compare these two sets of code


With Range(“A1:C8”)
Range(“A1:C8”).Interior.Color = vbRed .Interior.Color = vbRed
Range(“A1:C8”).Font.Bold = True .Font.Bold = True
Range(“A1:C8”).Font.Name = “Arial” .Font.Name = “Arial”
Range(“A1:C8”).Borders(xlEdgeBottom) .Borders(xlEdgeBottom).
.LineStyle = xlDash LineStyle = xlDash
End With

v Use Sheet4 to practice the application of the With construct


32
Referencing Ranges in VBA
v There are several ways to reference ranges and cells using
VBA
– Offset
– Cells
– Rows
– Columns
– EntireRow
– EntireColumn
– End

33
Offset vs. Cells
The resulting effect of using the offset property is proportional to the original size
of the range of cells. This means that if we offset using a cell range of size 2x2 as
v The Offset property a reference, the effect will also be shown as a cell range of size 2x2 offset
accordingly.
– Considers the upper left-most cell in the range (could be a named
range) to be in the 0th row and 0th column
– It offsets the range selection downward by a certain row count (if
positive) or upward (if negative) of the range
– It offsets the range selection to the right by a certain column count (if
positive) or to the left (if negative) of the range

34
Offset vs. Cells (cont.)
The resulting effect of using the cell property is not proportional to the original
size of the range of cells.
v The Cells property
– Considers the upper left-most cell in the range (could be a named
range) to be in the 1st row and 1st column
– It then finds the cell in the xth row position below (if the position
change is positive) or above (if the position change is negative) and
the yth column position to the right (if the position change is positive)
or left (if the position change is negative) of the range

35
Offset vs. Cells (cont.)
v In Class Exercise
– Use the Offset and Cells properties to achieve the results shown
below in Sheet5 (use E5 as reference cell)

36
Offset vs. Cells comparison

Offset Property Cells Property


v Upper left cell in v Upper left cell in
reference range reference range
coordinates (0,0) coordinates (1,1)

v Resulting range v Resulting range NOT


proportional to reference proportional to reference
range range (1 cell only)

37
Columns and Rows
v Columns and Rows, reference columns and rows in a
named range, respectively
– Both properties take a numerical index value to find the numbered
column within the named range
– Both properties consider the first column or row in the range to be
indexed as 1

38
EntireColumn and EntireRow
v EntireColumn and EntireRow, are used to modify every
column or row in the range for the length of the column or
row of the entire worksheet

v The EntireColumn property will affect every column in the


range and the EntireRow property will affect every row in
the range for their entire respective length
Range("B2").EntireRow.Select
Range("C3:D3").EntireColumn.Select

Range("A3:H30").Row 'Referring
Columns(5).Select to the row; returns 3
Rows(3).Select Range("B3").Column 'Referring
to the column; returns 2
39
End
v End is a very useful property as it can help you find the end
of a row or a column of any range of data

v The End property can take four values


– For columns
§ xlToRight and xlToLeft
Return last row number of selection
– For rows Selection.Cells(1, 1).End(xlDown).Row
§ xlDown and xlUp

v You do not need to name an entire data range to use this


property, just one cell in the data range is fine

40
Naming Ranges
v The most common way to assign object names is by using
the Name property To delete a named range in Excel VBA, we do the following:
ThisWorkbook.Names(“NamedRange”).Delete

v When you name a cell in Excel using Formulas > Define


Name > Define Name…, the name appears in the name
window whenever the corresponding range is selected
– The same occurs after naming a range in VBA

Range("C30").name = "datarange"
Range("datarange").Interior.Color = vbYellow

41
Naming Ranges (cont.)
v In Class Exercise
– Practice using the Name property using the data entered in Sheet5

42
Formulas with the Range Object

v Two main properties can be used with the Range object


– Formula
§ Value = reference by column letter and row number
– FormulaR1C1
§ Value = reference by R1C1 Notation

v A cell or an entire range of cells can be used with these


properties

v There is also one method we can use with the Range object
concerning formulas
– AutoFill
§ Arguments = Destination, Type

43
Formulas with the Range Object (cont.)

v In Class Exercise
– We will calculate sums and averages using the data entered in
Sheet5
– We also use the AutoFill method to copy and paste formulas

44
Formulas with the Application Object

v The Application object uses the WorksheetFunction


property to set a function for a cell or range of cells

v The WorksheetFunction property has several sub


properties for almost all of the Excel functions
– Max
– Min
– Average
– Sum
– Count
– VLookup
Range("F2") =
WorksheetFunction.Sum(Range("B2:C7"))

45
Formulas with the Application Object (cont.)

v In Class Exercise
– We will use the WorksheetFunction property to perform calculations
using the data entered in Sheet5

46
Sort Method with the Range Object
v The Sort Method can be used with the Range object
– Arguments = Key1, Order1, Header, …

v Key1 – Specifies the sort field


v Order1 – Specifies the sort order for Key1
v Header – Specifies whether the first row contains header
information (XlNo is default)

v Ex:
Range(“A1:F10").Select
Selection.Sort key1:=Range(“C1"), order1:=xlAscending

47
Sort Method with the Range Object (cont.)
v In Class Exercise
– We will use the Sort method to sort the data entered in Sheet5

48
Conditional Formatting
v Also associated with formatting the Range object is the
FormatConditions object, which places conditional
formatting on a specified range of cells

v There are three main methods and several properties for this
object
– Add
– Modify
– Delete

Range("H9:H13").FormatConditions.Add(xlCellValue, xlLess, "=10").Font.Bold = True

49
Conditional Formatting (cont.)
v In Class Exercise
– Add another sheet to the file “Objects.xlsm” (Sheet6) and enter the
values shown below in the table labeled “Original data”
– Write VBA code to place a conditional format on the range of cells so
that any cell with a value less than 10 has a yellow fill and bold font

Original data Result

50
Workbooks and Worksheets
v Workbooks and Worksheets objects will not be manipulated
as often as Range objects

v However, there is one important method that both


Workbooks and Worksheets use
– Activate
§ Argument = (none)

v There is one important property that Worksheets often use


– Visible
§ Value = True or False

51
Workbooks and Worksheets (cont.)
v Activate method
– We want to take some values from workbook Workbook1 and
transfer them for analysis into workbook Workbook2

Workbook1 Workbook2

52
Workbooks and Worksheets (cont.)
v Activate method
– We need to write VBA code in a module in workbook Workbook2
§ Open both workbooks in Excel
§ Create a module in Workbook2

– The code added to the module needs to do the following


§ Activate workbook Workbook1
§ Use the Copy method of the Range object to copy the data
§ Activate workbook Workbook2
§ Paste the data

53
Workbooks and Worksheets (cont.)
v Visible property
– We will use this property of the Worksheets objects to hide and show
worksheets as we navigate the user through our Excel-based
applications
– The code to accomplish this effect should be written in a sub
procedure associated with the Open event of the Workbook object

54
Workbooks and Worksheets (cont.)
v In-Class Exercise
– Use the Excel file “Objects.xlsm” created previously
– Go to the VBE editor
§ Inside the Project Explorer window, locate the object ThisWorkbook
§ Double click on the object
– Write code in the Open event so that Sheet2 and Sheet3 are hidden
the next time the workbook is opened
– Save and close your workbook
– Re-open the workbook and see the resulting effect

55
Summary
v Several methods and properties were covered for the
following objects
– Workbooks and Worksheets
– Ranges
– Application
v There are several properties of the Range object to
reference ranges and cells
v The With construct can help reduce code when modifying
several properties of one object
v Formulas can be created in VBA by using properties of the
Range object and the Application object

56

You might also like