用InStr函數(shù)實現(xiàn)代碼減肥

字號:

可以采用“旁門左道”的方式使用Instr函數(shù)實現(xiàn)代碼的簡練。下面是一個典型的例子,檢測字符串中是否包含一個元音字母:
    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、更加簡練的方法:
    If InStr("AaEeIiOoUu", char) Then
    ' it is a vowel
    End If
    同樣,通過單詞中沒有的字符作為分界符,使用InStr來檢查變量的內(nèi)容。下面的例子檢查Word中是否包含一個季節(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、更加簡練的方法:
    If Instr(";winter;spring;summer;fall;", ";" & word & ";") Then
    ' it is a season's name
    End If
    有時候,甚至可以使用InStr來替代Select
    Case代碼段,但一定要注意參數(shù)中的字符數(shù)目。下面的例子中,轉(zhuǎn)換數(shù)字0到9的相應(yī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、更加簡練的方法:
    result = InStr(";zero;;one;;;two;;;three;four;;five;;six;;;seven;eight;nine;", ";" & LCase$(word) & ";") \ 6