MICROSOFT

EP04. “InStr Function InStr 函数”

首页 Microsoft 工具 Excel · VBA · String Manipulation · EP04
约 5 分钟· #EP04#Excel#String Manipulation
🔒 登录后可标记已读
  • InStr 函数用来找出一段文字在另一段文字里出现的位置
  • 讲基础用法、指定起始搜索位置、找不到时的返回值
  • 也讲怎么用 InStr 做「是否包含」判断,以及不区分大小写的搜索
  • 前置知识:不需要

重点内容


适用版本

桌面版通用(Excel 365 / 2021 / 2019 等)。


基础用法

Dim state As String
state = "Virginia"
MsgBox InStr(state, "gin")

结果:4("gin" 从第 4 个字符开始出现)。


指定起始搜索位置

Dim state As String
state = "South Carolina"
MsgBox InStr(state, "o")
MsgBox InStr(7, state, "o")

第一个 MsgBox 结果是 2(从头开始找,第一个 "o" 在第 2 位);第二个从第 7 个字符开始找,结果是 10(找到后面那个 "o")。


找不到时返回 0

Dim state As String
state = "Florida"
MsgBox InStr(state, "us")

结果:0("us" 不在 "Florida" 里)。


搭配 IF 做「是否包含」判断

Dim state As String, substring As String
state = Range("A2").Value
substring = Range("B2").Value
If InStr(state, substring) > 0 Then
    Range("C2").Value = "Found"
Else
    Range("C2").Value = "Not Found"
End If

不区分大小写搜索

Dim state As String, substring As String
state = Range("A2").Value
substring = Range("B2").Value
If InStr(1, state, substring, vbTextCompare) > 0 Then
    Range("C2").Value = "Found"
Else
    Range("C2").Value = "Not Found"
End If

加上 vbTextCompare 参数(此时起始位置参数不能省略),搜索就不再区分大小写。


学完你会

  • ✅ 用 InStr 找出子字符串在字符串里的位置,知道找不到时返回 0
  • ✅ 用第一个参数指定起始搜索位置,跳过前面已经找过的部分
  • ✅ 搭配 vbTextCompare 做不区分大小写的搜索

常见错误

  • 忘记 InStr 找不到时返回的是 0,不是空字符串或报错,判断条件写错
  • 想用 vbTextCompare 却漏写前面的起始位置参数,导致语法错误
  • InStr(a, b)(在 a 里找 b)的参数顺序搞反

Sources

Blog / Website:

  1. InStr