![]() ![]() |
|
用InStr函数实现代码减肥 | |
作者:佚名 文章来源:不详 点击数 更新时间:2008/5/9 19:02:28 文章录入:杜斌 责任编辑:杜斌 | |
|
|
可以采用“旁门左道”的方式使用Instr函数实现代码的简练。下面是一个典型的例子,检测字符串中是否包含一个元音字母: 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来检查变量的内容。下面的例子检查Word中是否包含一个季节的名字: 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代码段,但一定要注意参数中的字符数目。下面的例子中,转换数字0到9的相应英文名称为阿拉伯数字: 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 |
|
![]() ![]() |