VBA Instr()函數

InStr()函數返回一個字串第一次出現在一個字串,從左到右搜索。返回搜索到的字元索引位置。

語法

InStr([start,]string1,string2[,compare])

參數說明

  • Start - 一個可選參數。指定搜索的起始位置。搜索從第一個位置開始,從左到右。
  • String1 - 必需的參數。要搜索的字串。
  • String2 - 必需的參數。要在String1中搜索的字串。
  • Compare - 一個可選參數。指定要使用的字串比較。它可以採取以下提到的值:
    • 0 = vbBinaryCompare - 執行二進位比較(默認)
    • 1 = vbTextCompare - 執行文本比較

示例

參考以下代碼 -

Private Sub Constant_demo_Click()
   Dim Var As Variant
   Var = "Microsoft VBScript"
   MsgBox ("Line 1 : " & InStr(1, Var, "s"))
   MsgBox ("Line 2 : " & InStr(7, Var, "s"))
   MsgBox ("Line 3 : " & InStr(1, Var, "f", 1))
   MsgBox ("Line 4 : " & InStr(1, Var, "t", 0))
   MsgBox ("Line 5 : " & InStr(1, Var, "i"))
   MsgBox ("Line 6 : " & InStr(7, Var, "i"))
   MsgBox ("Line 7 : " & InStr(Var, "VB"))
End Sub

當你執行上面的函數時,它會產生下麵的輸出。

Line 1 : 6
Line 2 : 0
Line 3 : 8
Line 4 : 9
Line 5 : 2
Line 6 : 16
Line 7 : 11

上一篇: VBA字串 下一篇: VBA日期時間函數