可以采用“旁門(mén)左道”的方式使用Instr函數(shù)實(shí)現(xiàn)代碼的簡(jiǎn)練。下面是一個(gè)典型的例子,檢測(cè)字符串中是否包含一個(gè)元音字母:
1、普通的方法:
If UCase$(char) = "A" Or UCase$(char) = "E" Or UCase$(char) = "I" Or UCase$(char) = "O" Or UCase$(char) = "U" Then
' it is a vowel
End If
2、更加簡(jiǎn)練的方法:
If InStr("AaEeIiOoUu", char) Then
' it is a vowel
End If
同樣,通過(guò)單詞中沒(méi)有的字符作為分界符,使用InStr來(lái)檢查變量的內(nèi)容。下面的例子檢查Word中是否包含一個(gè)季節(jié)的名字: 1、普通的方法:
If LCase$(word) = "winter" Or LCase$(word) = "spring" Or LCase$(word) = _ "summer" Or LCase$(word) = "fall" Then
' it is a season's name
End If
2、更加簡(jiǎn)練的方法:
If Instr(";winter;spring;summer;fall;", ";" & word & ";") Then
' it is a season's name
End If
有時(shí)候,甚至可以使用InStr來(lái)替代Select
Case代碼段,但一定要注意參數(shù)中的字符數(shù)目。下面的例子中,轉(zhuǎn)換數(shù)字0到9的相應(yīng)英文名稱(chēng)為阿拉伯?dāng)?shù)字: 1、普通的方法:
Select Case LCase$(word)
Case "zero"
result = 0
Case "one"
result = 1
Case "two"
result = 2
Case "three"
result = 3
Case "four"
result = 4
Case "five"
result = 5
Case "six"
result = 6
Case "seven"
result = 7
Case "eight"
result = 8
Case "nine"
result = 9
End Select
2、更加簡(jiǎn)練的方法:
result = InStr(";zero;;one;;;two;;;three;four;;five;;six;;;seven;eight;nine;", ";" & LCase$(word) & ";") \ 6
1、普通的方法:
If UCase$(char) = "A" Or UCase$(char) = "E" Or UCase$(char) = "I" Or UCase$(char) = "O" Or UCase$(char) = "U" Then
' it is a vowel
End If
2、更加簡(jiǎn)練的方法:
If InStr("AaEeIiOoUu", char) Then
' it is a vowel
End If
同樣,通過(guò)單詞中沒(méi)有的字符作為分界符,使用InStr來(lái)檢查變量的內(nèi)容。下面的例子檢查Word中是否包含一個(gè)季節(jié)的名字: 1、普通的方法:
If LCase$(word) = "winter" Or LCase$(word) = "spring" Or LCase$(word) = _ "summer" Or LCase$(word) = "fall" Then
' it is a season's name
End If
2、更加簡(jiǎn)練的方法:
If Instr(";winter;spring;summer;fall;", ";" & word & ";") Then
' it is a season's name
End If
有時(shí)候,甚至可以使用InStr來(lái)替代Select
Case代碼段,但一定要注意參數(shù)中的字符數(shù)目。下面的例子中,轉(zhuǎn)換數(shù)字0到9的相應(yīng)英文名稱(chēng)為阿拉伯?dāng)?shù)字: 1、普通的方法:
Select Case LCase$(word)
Case "zero"
result = 0
Case "one"
result = 1
Case "two"
result = 2
Case "three"
result = 3
Case "four"
result = 4
Case "five"
result = 5
Case "six"
result = 6
Case "seven"
result = 7
Case "eight"
result = 8
Case "nine"
result = 9
End Select
2、更加簡(jiǎn)練的方法:
result = InStr(";zero;;one;;;two;;;three;four;;five;;six;;;seven;eight;nine;", ";" & LCase$(word) & ";") \ 6