VBA是一種可以編寫宏來自動執行Microsoft Office應用程序中常見任務的編程語言。在使用VBA時,我們常常需要使用一些判斷語句來確定程序的執行條件,從而實現更加靈活的程序設計。本文將就多個方面來詳細介紹VBA中的判斷語句。
一、VBA判斷語句
VBA中的判斷語句主要有if語句和select case語句。if語句可以根據條件的真假來執行不同的語句塊,如下所示:
Sub ExampleIf()
Dim i As Integer
i = 5
If i > 10 Then
MsgBox i & " is greater than 10"
Else
MsgBox i & " is less than or equal to 10"
End If
End Sub
select case語句則可以根據一個表達式的值來執行不同的語句塊,如下所示:
Sub ExampleSelectCase()
Dim i As Integer
i = 2
Select Case i
Case 1
MsgBox "i = 1"
Case 2
MsgBox "i = 2"
Case Else
MsgBox "i is not 1 or 2"
End Select
End Sub
二、VBA判斷一個數據是否存在數組中
在VBA中,我們可以使用inStr函數來判斷一個數據是否存在於數組中,如下所示:
Sub ExampleInStr()
Dim Arr() As String
Arr = Split("apple,pear,orange", ",")
If InStr(1, Arr(0), "a", vbTextCompare) Then
MsgBox "The letter 'a' is in the first element of the array."
End If
End Sub
三、VBA判斷數組為空
我們可以使用UBound函數來判斷數組是否為空,如下所示:
Sub ExampleUBound()
Dim Arr() As String
If UBound(Arr) < 0 Then
MsgBox "The array is empty."
End If
End Sub
四、VBA判斷一個數字是否在一個集合里
在VBA中,我們可以使用InStr函數來判斷一個數字是否在一個集合中,如下所示:
Sub ExampleInStr2()
Dim s As String
s = "1,2,3,4,5"
If InStr(1, s, "3", vbTextCompare) Then
MsgBox "The number 3 is in the collection."
End If
End Sub
五、VBA判斷是否為數字
在VBA中,我們可以使用IsNumeric函數來判斷一個變量是否為數字,如下所示:
Sub ExampleIsNumeric()
Dim s As String
s = "123"
If IsNumeric(s) Then
MsgBox "The variable 's' is numeric."
End If
End Sub
六、VBA判斷日期在某個區間
在VBA中,我們可以使用DateValue函數來將一個字符串轉換為日期格式,然後使用And和Or運算符來判斷日期是否在某個區間內,如下所示:
Sub ExampleDateValue()
Dim d As Date
d = DateValue("2021/01/01")
If d >= DateValue("2021/01/01") And d <= DateValue("2022/01/01") Then
MsgBox "The date is within the specified range."
End If
End Sub
七、VBA判斷題
在VBA中,我們可以使用True和False關鍵字來代表真和假,從而進行判斷,如下所示:
Sub ExampleTrueOrFalse()
Dim b As Boolean
b = True
If b Then
MsgBox "The variable 'b' is True."
Else
MsgBox "The variable 'b' is False."
End If
End Sub
八、VBA判斷sheet存在
在VBA中,我們可以使用WorksheetFunction函數的CountIf方法來判斷sheet是否存在,如下所示:
Sub ExampleWorksheetFunction()
Dim sheetName As String
sheetName = "Sheet1"
If WorksheetFunction.CountIf(ThisWorkbook.Sheets("Sheet1").Range("A1"),"=IFERROR(1/0,"""")") > 0 Then
MsgBox sheetName & " exists."
Else
MsgBox sheetName & " does not exist."
End If
End Sub
九、VBA判斷是否為小數
在VBA中,我們可以使用Mod函數來判斷一個數是否為小數,如下所示:
Sub ExampleMod()
Dim d As Double
d = 1.5
If d Mod 1 = 0 Then
MsgBox "The number is not a decimal."
Else
MsgBox "The number is a decimal."
End If
End Sub
十、VBA判斷是否為字符串
在VBA中,我們可以使用IsNumeric函數來判斷一個變量是否為字符串,如下所示:
Sub ExampleIsNumeric2()
Dim s As String
s = "Hello"
If Not IsNumeric(s) Then
MsgBox "The variable 's' is a string."
End If
End Sub
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/239396.html