Upload
vicente-audley
View
224
Download
0
Embed Size (px)
Citation preview
Variant “Data Type”
• In VB you don’t have to declare variable before its usage– Then, VB will by itself declare such variable as “Variant”
• You can also declare variable as “Variant”– Dim myVar as Variant
• Variant – means that the variable may contain any data type
Variables Assignment
• To assign a value to a Numeric or String type Variable, you simply use your Variable name, followed by the equals sign (=) and then the String or Numeric
• To assign an Object to an Object type variable you must use the key word "Set"
Variables Assignment – cont.Sub ParseValue()
Dim varName as String varName = “Cuong Do”
Dim varAge as Integer varAge = “28”
Dim varCell as Range Set varCell = Range("A1")
varCell.Value = “123”End Sub
VBA Variables Scope & LifecycleThe scope & lifecycle of a variable defines the code where the variable can be accessed and time when the stored data is kept inside the variable
• Procedure-Level– Variables defined inside procedures– Can be accessed only inside the procedure and keep their data until the
End statement of the procedure• Module-Level
– Defined in the top of a Module– Any procedure inside the Module can access the variable– The variable retains the values unless the Workbook closes
• Project-Level, Workbook Level, or Public Module-Level– Defined as “Public” in the top of a Module– Can be accesses by any procedure in any module– The variable retains the values unless the Workbook closes
VBA Variables Scope & Lifecycle – cont.
• Sub scopeExample()Dim x as Integerx = 5
End Sub• Dim y as Integer
‘all the module procedures are here…• Public z as Integer
‘all the module procedures are here…
Procedure level variables
Module level variables
Project level variables
Basic Excel Classes
• Workbook: the class represents an Excel file• Worksheet: represents a single worksheet• Cell: represents a single cell
Excel Containers
• Workbooks: a collection of objects of class “Workbook”
• Worksheets: a collection of objects of class “Worksheet”
• Range: a range of objects of class Cell
Referring to Cells by Using a Range Object
Sub Random() Dim myRange As Range Set myRange =
Worksheets("Sheet1").Range("A1:D5") myRange.Formula = "=RAND()" myRange.Font.Bold = True
End Sub
Referring to Cells by Using a Range Object
Sub Test1()Range("A10").Value = "123"End Sub
Sub Test2()Set varRange = Range("A10")varRange.Value = "123"End Sub
Sub Test3()Worksheets(1).Range("A10") = "123"End Sub
Sub Test4()Worksheets("Sheet1").Range("A10") = "123"End Sub
Same outcome
here
Referring to Multiple Ranges
Sub ClearRanges() Worksheets("Sheet1")._ Range("C5:D9,G9:H16,B14:D18").ClearContents
End Sub
Referring to Cells by Using Index Numbers
• Cells indexing format:– Cells(row, column), where both row and column are given
as integers (starting from 1)
– Cells(index)
Sub EnterValue() Worksheets("Sheet1").Cells(6, 1).Value = 10End Sub
Sub EnterValue() Worksheets(1).Range("A1:D3").Cells(7) .Value = "Here it is"End Sub
Some useful methods/properties of Excel Classes
• Workbooks.Close – closes the active workbook• Workbooks.Count – returns the number of currently
open workbooks• Range(“A1”) is the same as Range(“A1”).Value• Cells(1,1) is the same as Cells(1,1).Value• Worksheets(1).Column(“A:B”).AutoFit • Worksheets(1).Range(“A1:A10”).Sort_• Workbooks.Open fileName:=“test.xls”
Multidimensional Arrays
Dim Grades(1 to 5,1 to 2) Grades(1,1)=“Jack”Grades(1,2)=“A”Grades(2,1)=“Nick”Grades(2,2)=“B”For i=1 to 2
MsgBox Grades(i,1) & “ got ” & Grades(i,2)NextMsgBox Grades(1, 1) & " got " & Grades(1, 2) & vbCrLf & _ Grades(2, 1) & " got " & Grades(2, 2)
Resizing the Arrays
Dim Grades(1 to 5,1 to 2) Grades(1,1)=“Jack”Grades(1,2)=“A”Grades(2,1)=“Nick”Grades(2,2)=“B”‘ Now ReDim the arrayReDim Grades(1 to 10,1 to 2) ‘previous values won’t be keptReDim Preserve Grades(1 to 10,1 to 2) ‘preserve previous values
Only the first dimension can be changed!
Upper & Lower Index Bounds of an Array
• Dim A(3): index from 0 to 3• Dim A(1 to 3): index from 1 to 3• Dim A(1 To 100, 0 To 3, -3 To 4)
– UBound(A, 1) – will return “100”– UBound(A, 2) – will return “3”– UBound(A, 3) – will return “4”– LBound(A, 1) – will return “1”– LBound(A, 2) – will return “0”– LBound(A, 3) – will return “-3”
VBA Control Structures - If• If Grade >= 90 Then MsgBox "You got an A"
ElseIf Grade >= 80 Then MsgBox "You got a B" ElseIf Grade >= 70 Then MsgBox "You got a C" Else
MsgBox "You are out of scope”End If Need to capture the rest of cases
VBA Control Structures – Select
• Select Case Grade Case Is >= 90 MsgBox "You got an A Case Is >= 80 MsgBox "You got an B” Case Is >= 70 MsgBox "You got a C” Case Else MsgBox "You out of scope”End Select Need to capture the rest of cases
VBA Control Structures – LoopsSub factorial1()Dim NN = 10Cells(1, 1) = 1For i = N To 1 Step -1 Cells(1, 1) = Cells(1, 1) * iNextEnd Sub
Sub factorial3()Dim NN = 10i = NCells(1, 3) = 1Do Cells(1, 3) = Cells(1, 3) * i i = i - 1Loop While i >= 1End Sub
Sub factorial2()Dim NN = 10i = NCells(1, 2) = 1Do While i >= 1 Cells(1, 2) = Cells(1, 2) * i i = i - 1LoopEnd Sub
N!
Loop at least once
Loops for Collection Objects
Sub WorkSheetsLoop() Dim mySheet As Worksheet For Each mySheet In Worksheets MsgBox mySheet.Name Next mySheet
End Sub
Nested Loops Example
Sub NestedLoopExample() For i = 1 To 5 For j = 1 To 5 Cells(i, j) = "Row " & i & " Col " & j Next j Next i
End Sub
Worksheet functions
Sub FuncExample()Range("D6") = Application. WorksheetFunction. Sum(Range("D1:D5"))‘ Can also use Application. Sum for shortEnd Sub
‘ Another way to get the sumRange("D6").Formula = "=SUM(D1:D5)"
Other Issues in VBA programming
• What if need to pass an array of arguments without knowing the number of arguments
GraphsPrivate Sub cmdGenerate_Click()Range("B2:E13").Formula = "=RAND()*100"End Sub
Private Sub cmdPlot_Click() Create_Chart_SheetEnd Sub
Sub Create_Chart_Sheet() Charts.Add With ActiveChart .ChartType = xlColumnClustered .SetSourceData Source:=Sheets("Sheet4").Range("B1:E13") End WithEnd Sub