InStr 函数
返回某字符串在另一字符串中第一次出现的位置。
[code][b]InStr([/b][start, ]string1, string2[, compare][b])[/b][/code]
[h3]参数[/h3]start
可选项。数值表达式,用于设置每次搜索的开始位置。如果省略,将从第一个字符的位置开始搜索。如果 [b]start[/b] 包含 Null,则会出现错误。如果已指定 [b]compare[/b],则必须要有 [b]start[/b] 参数。
string1
必选项。接受搜索的字符串表达式。
string2
必选项。要搜索的字符串表达式。
compare
可选项。指示在计算子字符串时使用的比较类型的数值。有关数值,请参阅“设置”部分。如果省略,将执行二进制比较。
[h3]设置[/h3][b]compare[/b] 参数可以有以下值:
| 常数 | 值 | 描述 |
|---|
| vbBinaryCompare | 0 | 执行二进制比较。 |
| vbTextCompare | 1 | 执行文本比较。 |
[h3]返回值[/h3][b]InStr[/b] 函数返回以下值:
| 如果 | InStr 返回 |
|---|
| string1 为零长度 | 0 |
| string1 为 Null | Null |
| string2 为零长度 | start |
| string2 为 Null | Null |
| string2 没有找到 | 0 |
| 在 string1 中找到 string2 | 找到匹配字符串的位置 |
| start > Len(string2) | 0 |
[h3]说明[/h3]下面的示例利用 [b]InStr[/b] 搜索字符串:
[code]Dim SearchString, SearchChar, MyPosSearchString ="XXpXXpXXPXXP" ' String to search in.SearchChar = "P" ' Search for "P".MyPos = [b]Instr([/b]4[b],[/b] SearchString[b],[/b] SearchChar[b],[/b] 1[b])[/b][/code] [code]' A textual comparison starting at position 4. Returns 6.[/code][code]MyPos = [b]Instr([/b]1[b],[/b] SearchString[b],[/b] SearchChar[b],[/b] 0[b])[/b][/code] [code]' A binary comparison starting at position 1. Returns 9. [/code][code]MyPos = [b]Instr([/b]SearchString[b],[/b] SearchChar[b])[/b][/code] [code]' Comparison is binary by default (last argument is omitted). Returns 9.[/code][code]MyPos = [b]Instr([/b]1[b],[/b] SearchString[b],[/b] "W"[b])[/b][/code] [code]' A binary comparison starting at position 1. Returns 0 ("W" is not found).[/code][b]注意[/b] [b]InStrB[/b] 函数使用包含在字符串中的字节数据,所以 [b]InStrB[/b] 返回的不是一个字符串在另一个字符串中第一次出现的字符位置,而是字节位置。