' Multiline syntax:
If condition [ Then ] [ statements ]
[ ElseIf elseifcondition [ Then ] [ elseifstatements ] ]
[ Else [ elsestatements ] ]
End If ' Single-line syntax:
If condition Then [ statements ] [ Else [ elsestatements ] ]
舉個例子 閏年判斷
Dim y As Long
y = Year(Now)
If y Mod 400 = 0 ThenMsgBox Str(y) & "是閏年"
ElseIf y Mod 4 = 0 And y Mod 100 <> 0 ThenMsgBox Str(y) & "是閏年"
ElseMsgBox (Str(y)) & "是平年"
End If
3、函數 基本語法
[Private][Public][Static]Function <函數過程名>([形參列表])[As <類型>]<語句系列>[<函數名> = <表達式>]
[Exit Function]
[<語句系列>]
[<函數名> = <表達式>]
End Function
Function isPrime(ByVal num As Long) As Boolean
Dim tmp As Double
isPrime = True
If num = 1 ThenisPrime = False
Elsetmp = Sqr(num)For i = 2 To tmpIf num Mod i = 0 ThenisPrime = FalseExit ForEnd IfNext
End If
End Function
4、日期 詳細可見博客1,博客2 程序中使用到的
Date,Time,Now函數:讀取系統的日期時間
格式化時間 Format(date, dateformat)
將字符串轉為date CDate(dateStr)
year(T), month(T), day(T), weekday(T)
Dim dt As Date, dateStr As String, datas As String
dates = "2019-04-08"
dateStr = Format(dt, "yyyy-mm-dd hh.mm.ss") '將時間類型指定格式的字符串
week = Weekday(CDate(dates)) '將字符串轉為Date類型,再獲取星期幾
5、字符串 詳細見博客
mid(字符串, idx,len) ByRef 從字符串idx處,取出長度為len的子串
trim(str) ByVal去掉字符串前后的空格
len(str) ByVal 返回字符串的長度
Join(list[, delimiter]) As String 返回一個字符串,該字符串是通過連接某個數組中的多個子字符串而創建的。list 必需的。包含被連接子字符串的一維數組。delimiter 可選的。在返回字符串中用于分隔子字符串的字符。如果忽略該項,則使用空格(" ")來分隔子字符串。如果delimiter是零長度字符串(""),則列表中的所有項目都連接在一起,中間沒有分隔符。
Split(str[, delimiter]) 返回的是一個字符串數組 ,默認分隔符為" "
Dim timeStr As String, timeArr() As String, h As String, m As String, s as String
timeStr = "12:23:34"
'獲取時,分,秒
'1、用字符串分隔的方法
timeArr = Split(timeStr, ":")
h = Val(timeArr(0))
m = Val(timeArr(1))
s = Val(timeArr(2))
'2、用mid來截取字符串
h = Val(Mid(timeStr(i), 1, 2)) '獲取小時
m = Val(Mid(timeStr(i), 4, 2)) '獲取分鐘
s = Val(Mid(timeStr(i), 7, 2)) '獲取秒
'根據學生與老師的關系生成mapFor i = 2 To relaRowsIf relation(i, 1) <> "" And relation(i, 5) <> "" ThenDim tea As String, stu As Stringtea = relation(i, 5)stu = relation(i, 1)stuCol.Add tea, stuIf exists(teaCol, tea) = False ThenDim arr() As StringReDim arr(0)arr(0) = stuteaCol.Add arr, teaElse'若已在teaCol中存在,則先刪除Item,再添加arr = teaCol.Item(tea)ReDim Preserve arr(UBound(arr) + 1)arr(UBound(arr)) = stuteaCol.Remove (tea)teaCol.Add arr, teaEnd IfElsemyNum = myNum + 1End IfNext
如果直接訪問集合中不存在的元素,VB會直接報錯,所以在使用元素之前,需判斷集合中的元素是否存在。
'判斷元素是否在集合
'Collection中的元素為數組
Function exists(pCol As Collection, pKey As String) As Boolean
On Error Resume Nextexists = (UBound(pCol(pKey)) >= 0)
End Function
'Collection中的元素為字符串
Function exists1(pCol As Collection, pKey As String) As Boolean
On Error Resume Nextexists1 = Len(pCol(pKey) >= 0)
End Function