Presentation is loading. Please wait.

Presentation is loading. Please wait.

VBA Navigation, Conditionals, and Boxes. VBA Navigation.

Similar presentations


Presentation on theme: "VBA Navigation, Conditionals, and Boxes. VBA Navigation."— Presentation transcript:

1 VBA Navigation, Conditionals, and Boxes

2 VBA Navigation

3 Background: Objects and Methods  Objects  Data-centric objects are structures that contain data and a set of predefined methods that manipulate the data. The following are examples of data-centric objects: a range of cells, an Excel worksheet, and a cell in a worksheet.  Tool-centric objects are tools with specific functionality that can be added to a workbook; e.g., button, form, textbox, etc.  Methods  Methods are a set of predefined actions that can be performed on the data contained in the object. Methods are tied directly to an object. They occur when an action takes place upon that object. They do not exist independent of that object.  A few of the many methods available for the Range object include the following: ClearContents, ClearFormats, Cut, Copy, Delete, Replace, and Select.

4 Background: Properties  Properties  Properties are characteristics of an object. In other words, a property is a piece of information that describes some aspect of an object (e.g., the value of a cell, the number of columns in a Range, the width of a column, etc.).  A few of the many properties available for the Range object include the following: Columns, Rows, ColumnWidth, Offset, Value, and VerticalAlignment.  In VBA code, methods and properties follow the object name. At first glance, this may seem backwards, but this sequence is common for object-oriented languages.

5 Within-Worksheet Navigation  Select method  Select method with Absolute References  Range(“ ”).Select To SelectExample A single cell Range("A3").Select A range of contiguous cells Range("B3:B6").Select Range("B3", "B6").Select Non-contiguous cells Range("A1,A5,B4").Select

6 Within-Worksheet Navigation  Select method  Select method with Relative References  [Origination Location].Offset(RowOffset,ColumnOffset)  RowOffset indicates the number of rows to move from the current location.  ColumnOffset indicates the number of columns to move from the current location.  Offset property requires an original location To MoveExample One cell down (e.g., from B2 to B3) Range("B2").Offset(1,0).Select One cell to the right (e.g., from B2 to C2) Range("B2").Offset(0,1).Select One cell up (e.g., from B2 to B1) Range("B2").Offset(-1,0).Select One cell to the left (e.g., from B2 to A2) Range("B2").Offset(0,-1).Select Five rows down and six columns right Range("A1").Offset(5,6).Select Origination PointExample Absolute reference Range("A1").Offset(2,3).Select Active cell Activecell.Offset(2,3).Select

7 Automatically finding the end of Ranges  It is often very useful to automatically find the end of a continuous data range. Consider the spreadsheet. The code must automatically determine how many employee records to process each pay period, since the number of employees is likely to change over time.  The code should begin at cell A3 and find the last non-blank value in column A. When using a computer keyboard, if you select cell A3 and then press CTRL+↓, the active cell will move to A6.

8 Automatically finding the end of Ranges  The table below shows keyboard shortcuts along with VBA equivalents for finding boundaries in a range  The following code begins at A3, finds, and returns the lowest non-empty row below the starting point. The number returned is 6.  lastrow = Range("A3").End(xlDown).Row Keystrok es VBA EquivalentWhat it Finds Ctrl+↓ Range.End(xlDown)Lowest non-blank row in range. Ctrl+↑ Range.End(xlUp)Highest non-blank row in range. Ctrl+→ Range.End(xlToRight)Right-most non-blank column in the range. Ctrl+← Range.End(xlToLeft)Left-most non-blank column in the range

9 Using the Application Command to enable use of Worksheet functions  The Application key word allows VBA to apply an Excel worksheet function right in the VBA code.  This will calculate the sum of the cells in the range from B3 to the lowest contiguous value below cell B3 (B6 in this case). The portion of the code on the right selects the entire range. The code on the left side invokes the worksheet function to process the contents of the range.  Sum1 = Application.Sum(Range("B3", Range("B3").End(xlDown)))  This finds the average of the same range of cells.  Avg1 = Application.Average(Range("B3", Range("B3").End(xlDown)))

10 Referencing Non-Selected Cells  In this example spreadsheet, the Tax Amount and Net Pay are to be calculated for each employee:  The Offset parameter can be used to get data from a non-selected cell or to write data to non-selected cell. In other words, one location can be selected and Offset can be used to do work on cells that are nearby but that are not selected.

11 Referencing Non-Selected Cells 01 Sub NetPay() 02 03 Dim GrossPay As Currency, TaxRate As Currency 04 Dim TaxAmount As Currency, NetPay As Currency 05 Range("A3").Select 06 GrossPay = ActiveCell.Offset(0, 1).Value‘the Offset parameter is used with Value parameter to get values out of non- ‘selected cells 07 TaxRate = ActiveCell.Offset(0, 2).Value 08 TaxAmount = GrossPay * TaxRate 09 NetPay = GrossPay - TaxAmount 10 ActiveCell.Offset(0, 3).Value = TaxAmount‘the Offset parameter is also used with the Value parameter to ‘write values into non-selected cells 11 ActiveCell.Offset(0, 4).Value = NetPay 12 ActiveCell.Offset(1, 0).Select ‘Select moves to the next record 13 14 End Sub

12 Referencing Non-Selected Cells 01 Sub NetPay() 02 03 Dim GrossPay As Currency, TaxRate As Currency 04 Dim TaxAmount As Currency, NetPay As Currency 05 Range("A3").Select 06 Do Until IsEmpty(Selection.Value)‘Loop repeats until cell value is empty 07 GrossPay = ActiveCell.Offset(0, 1).Value 08 TaxRate = ActiveCell.Offset(0, 2).Value 09 TaxAmount = GrossPay * TaxRate 10 NetPay = GrossPay - TaxAmount 11 ActiveCell.Offset(0, 3).Value = TaxAmount 12 ActiveCell.Offset(0, 4).Value = NetPay 13 ActiveCell.Offset(1, 0).Select 14 Loop 15 16 End Sub

13 Navigation between tabs within the same Workbook  The names on the left (e.g., Sheet1, Sheet2) are the default names assigned by Excel. The names on the right, e.g., (Output), (Input), are the names assigned by the user when the user decided to change the name of the tab to something other than the default name:  The Sheets command uses the user-assigned name. That is, the name on the right. The Sheets command lets you move among different worksheets (tabs) within the same workbook. It takes a single argument: the name of the sheet that you would like to select.  The following selects the worksheet named "Input". The next line selects cell A2 on that worksheet.  Sheets("Input").Select  Range("A2").Select

14 VBA Conditionals

15 If-Then-Else FlowchartVBA Code If-Then-Null-ElseIf MS > SG Then B = BP * MS End If If-Then-ElseIf ET = True Then GP = H * R Else GP = SA End If

16 Select Case Select Case test_variable Case condition_1 Code to run if condition_1 Case condition_n Code to run if condition_n Case Else Code to run if Else End Select

17 Select Case / If...Else If Select...Case Select Case LRegion Case "N" LRegionName = "North" Case "S" LRegionName = "South" Case "E" LRegionName = "East" Case Else LRegionName = "West" End Select If LRegion = "N" Then LRegionName = "North" ElseIf LRegion = "S" Then LRegionName = "South" ElseIf LRegion = "E" Then LRegionName = "East" Else 'Legion = "W" LRegionName = "West" End If

18 Select Case / If...Else If Select...Case using “To” keyword Select Case LNumber Case 1 To 10 LRegionName = "North" Case 11 To 20 LRegionName = "South" Case 21 To 30 LRegionName = "East" Case Else LRegionName = "West" End Select LNumber = 30 If LNum >= 1 And LNumber <= 10 Then LRegionName = "North" ElseIf LNum >= 11 And LNumber <= 20 Then LRegionName = "South" ElseIf LNum >= 21 And LNumber <= 30 Then LRegionName = "East" Else LRegionName = "West" End If

19 Select Case / If...Else If Select…Case Enumerating with commas Select Case LNum Case 1, 2 LRegionName = "North" Case 3, 4 LRegionName = "South" Case 5, 6 LRegionName = "East" Case 7, 8 LRegionName = "West" End Select f LNum = 1 Or LNum = 2 Then LRegionName = "North" ElseIf LNum = 3 Or LNum = 4 Then LRegionName = "South" ElseIf LNum = 5 Or LNum = 6 Then LRegionName = "East" Else LRegionName = "West" End If

20 Boxes

21 Input Box  An Input Box function displays an input box on top of the excel workbook, which allows the user to type a value into a dialog box. The content typed by the user into the input box is stored as string variable that will be remembered for later use in a procedure.  Variable = InputBox (Prompt, [Title])

22 Input Box 01 Sub Try() 02 Dim Ans As String 03 Ans = InputBox("Want milk (y/n)?", "Enter Data") 04 If Ans = Empty Then Exit Sub 05 If Ans = "y" Then 06 MsgBox "I'll get you a glass." 07 ElseIf Ans = "n" Then 08 MsgBox "I'll put the milk away." 09 Else 10 MsgBox "Unexpected input. Exiting…” 11 End If 12 End Sub

23 MsgBox  The VBA MsgBox function displays a message in a window on the computer screen over the top of the worksheet and waits for the user to click on a button. No additional lines of code execute until the user presses the OK button on the screen.  In concatenating text, the “&” operator is used to join strings. Sub getMonths() Dim Yrs As Integer, Mnths As Integer Yrs = 10 Mnths = Yrs * 12 MsgBox "You are " & Mnths & " months old." End Sub


Download ppt "VBA Navigation, Conditionals, and Boxes. VBA Navigation."

Similar presentations


Ads by Google