處理對象和集合
VBA編程要在處理對象和集合方面花費大量時間。VBA提供了兩個重要的結構,可以簡化對象和集合的處理。
With-End With結構
With-End With結構適用于對單個對象執(zhí)行多項操作,可提高執(zhí)行速度。在錄制VBA宏時,Excel一旦有機會就會使用With-End With結構。以下兩段代碼等效:
Sub ChangeFont1()
Selection.Font.Name = "仿宋"
Selection.Font.Bold = True
Selection.Font.Italic = True
Selection.Font.Size = 14
Selection.Font.Underline = xlUnderlineStyleSingle
Selection.Font.ThemeColor= xlThemeColorAccentl
End Sub
Sub ChangeFont2()
With Selection.Font
.Name = "仿宋"
.Bold = True
.Italic = True
.Size = 14
.Underline = xlUnderlineStyleSingle
.ThemeColor= xlThemeColorAccentl
End With
End Sub
For Each-Next結構
“集合”是一組相關的對象。假設要在集合的所有對象上執(zhí)行某個動作,或要對集合的所有對象求值并在特定條件下采取動作,這些都是使用For Each-Next結構的好機會。使用For Each-Next機構時,不必知道集合中有多少個元素。
For Each-Next結構的語法如下("[]"內(nèi)表示可選,非必須):
For Each element In collection
[代碼]
[Exit For] '遍歷完所有元素之前可以退出循環(huán)
[代碼]
Next element
以下為示例:
Sub CountSheets()
'顯示打開的工作表名稱
Dim Item as Worksheet
For Each Item In ActiveWorkbook.Worksheets
MsgBox Item.Name
Next Item
End Sub
Sub ToUpper()
'把選中的單元格內(nèi)容轉換為大寫
Dim Cell As Range
Dim Cnt as Integer
Cnt = 0
For Each Cell In Selection
Cell.Value = UCase(Cell.Value)
Cnt = Cnt + 1
Next Cell
MsgBox "已完成所選" & Cnt & "個單元格內(nèi)容轉換。"
End Sub
Sub FirstNegative()
'找到并選中A1:A10區(qū)域第1個負數(shù)
Dim Cell As Range
For Each Cell In Range("A1:A10")
If Cell.Value < 0 Then
'如果單元格中為負值,則選中并結束循環(huán)
Cell.Select
Exit For
End If
Next Cell
End Sub
控制代碼執(zhí)行過程
VBA過程中需要控制代碼的執(zhí)行過程(流程),通過跳過某些語句、多次執(zhí)行某些語句或通過測試條件決定接下來做什么。上面的For Each-Next結構是一種循環(huán)結構,除此之外,VBA主要還有以下流程控制結構:
- If-Then 分支結構
- Select Case 分支結構
- For-Next 循環(huán)結構
- Do While 循環(huán)結構
- Do Until 循環(huán)結構
- GoTo 跳轉語句
If-Then分支結構
通過分支結構賦予程序決策能力,好的分支結構是成功編程的關鍵。If-Then分支機構用于有條件的執(zhí)行一條或多條語句,Else子句可選,若包含Else子句,那么當測試條件不是True時,Else子句執(zhí)行一條或多條語句。
單行語句示例:
If Time < 0.5 Then MsgBox "早上好!"
If Time < 0.5 Then MsgBox "早上好!" Else _
MsgBox "下午好!"
多行語句示例:
If Time < 0.5 Then
MsgBox "早上好!"
' 多行語句
End If
If Time < 0.5 Then
MsgBox "早上好!"
' 多行語句
Else
MsgBox "下午好!"
' 多行語句
End If
If Time < 0.5 Then
MsgBox "早上好!"
ElseIF Time >=0.5 And Time < 0.75 Then
MsgBox "下午好!"
Else
MsgBox "晚上好!"
End If
If Time < 0.5 Then
MsgBox "早上好!"
Else
IF Time >=0.5 And Time < 0.75 Then
MsgBox "下午好!"
Else
MsgBox "晚上好!"
End If
End If
Select Case分支結構
在三個或多個選項之間做出選擇時,Select Case結構很有用處,他是If-Then-Else結構很好的替代。
例如:
Sub GreetMe()
Dim Msg As String
Select Case Time
Case Is < 0.5
Msg = "早上好!"
Case 0.5 To 0.75
Msg = "下午好!"
Case Else
Msg = "晚上好!"
End Select
MsgBox Msg
End Sub
Sub GreetMe2()
Select Case Weekday(Now)
Case 2, 3, 4, 5, 6
MsgBox "今天是工作日!"
Case Else
MsgBox "周末愉快!"
End Select
End Sub
Sub GreetMe3()
Select Case Weekday(Now)
Case 2 To 6
MsgBox "今天是工作日!"
Case Else
MsgBox "周末愉快!"
End Select
End Sub
如果每個情況下只有一句指令,可以(通過VBA語句分隔符:冒號)把指令和關鍵字Case放在同一行,使代碼更簡潔:
Sub GreetMe3()
Select Case Weekday(Now)
Case 2 To 6 : MsgBox "今天是工作日!"
Case Else : MsgBox "周末愉快!"
End Select
End Sub
For-Next循環(huán)結構(計數(shù)循環(huán))
For-Next循環(huán)結構是最簡單的一種循環(huán)。語法如下("[]"內(nèi)表示可選,非必須):
For counter = start To end [Step stepval]
[代碼]
[Exit For]
[代碼]
Next counter
示例:
Sub SumSquareRoots()
'求前100個數(shù)的平方根總和
Dim Sum As Double
Dim Count As Integer
Sum = 0
For Count = 1 To 100
Sum = Sum + Sqr(Count)
Next Count
MsgBox Sum
End Sub
Sub DeleteRows()
' 刪除單元格行
Dim RowNum As Long
For RowNum = 10 To 2 Step -2
Rows(RowNum).Delete
Next RowNum
End Sub
Sub NestedLoops()
' 循環(huán)嵌套
Dim MyArray(1 to 10, 1 to 10, 1 to 10)
Dim i As Integer, j As Integer, k As Integer
For i = 1 To 10
For j = 1 To 10
For k = 1 To 10
MyArray(i, j, k) = 1
Next k
Next j
Next i
End Sub
Do While循環(huán)結構(條件循環(huán))
Do While循環(huán)是VBA中另一種循環(huán)結構,只有在滿足指定條件時才會執(zhí)行Do While循環(huán)。Do While循環(huán)有兩種語法結構,如下("[]"內(nèi)表示可選,非必須):
Do [While condition]
[代碼]
[Exit Do]
[代碼]
Loop
'或者
Do
[代碼]
[Exit Do]
[代碼]
Loop [While condition]
示例:
Sub EnterDate1()
' Do While, with test at the beginning
Dim TheDate As Date
TheDate = DateSerial(Year(Date),Month(Date),1)
Do While Month(TheDate) = Month(Date)
ActiveCell = TheDate
TheDate = TheDate + 1
ActiveCell.Offset(1, 0).Activate
Loop
End Sub
Do Until循環(huán)結構(條件循環(huán))
Do Until循環(huán)結構與Do While結構非常類似。Do Until一直執(zhí)行循環(huán),直到測試條件為True時結束循環(huán)。Do Until也有兩種語法格式("[]"內(nèi)表示可選,非必須):
Do [Until condition]
[代碼]
[Exit Do]
[代碼]
Loop
'或者
Do
[代碼]
[Exit Do]
[代碼]
Loop [Until condition]
示例:
Sub EnterDate2()
' Do Until, with test at the beginning
Dim TheDate As Date
TheDate = DateSerial(Year(Date),Month(Date),1)
Do Until Month(TheDate) <> Month(Date)
ActiveCell = TheDate
TheDate = TheDate + 1
ActiveCell.Offset(1, 0).Activate
Loop
End Sub
GoTo 跳轉語句
改變流程最直接的方式是使用GoTo語句,該語句只是將程序的執(zhí)行轉移到一條新的指令,必須要有標簽標識此指令(帶冒號的文本字符串貨不帶冒號的數(shù)字)。VBA過程可以包含任意數(shù)量的標簽,但是GoTo語句不能轉移到過程之外的指令。
一般只有沒其它辦法時才使用GoTo語句。除非進行錯誤處理,否則不建議使用GoTo語句。示例:
Sub GoToDemo()
UserName = InputBox("請輸入用戶名:")
If UserName <> "哎喂可樂" Then GoTo WrongName
MsgBox ("歡迎哎喂可樂……")
'更多代碼
Exit Sub
Wrong Name:
MsgBox "抱歉,只有哎喂可樂可以執(zhí)行此程序。"
End Sub