Sign in with Microsoft
Sign in or create an account.
Hello,
Select a different account.
You have multiple accounts
Choose the account you want to sign in with.

會傳回 Variant (Long),指定另一個字串內某個字串的第一個出現位置。

查看一些範例

語法

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

InStr 函數語法具有下列自變數:

引數

描述

開始

選擇性。 設定每個搜尋起始位置的數值表達式。 如果省略,搜尋會從第一個字元位置開始。 如果 start 包含 Null,則會發生錯誤。 如果指定 compare,則需要 start 自變數。

string1

必要。 正在搜尋字串表示式。

string2

必要。 尋找的字串表達式。

compare

選擇性。 指定 字串比較的類型。 如果 compare 為 Null,則會發生錯誤。 如果省略 compare[選項比較] 設定會決定比較的類型。 指定有效的 LCID (LocaleID) 在比較中使用地區設定特定規則。

提示: 表達式建立器具有 IntelliSense,因此您可以查看表示式需要哪些自變數。

設定

比較自變數設定為:

常數

描述

vbUseCompareOption

-1

使用 [選項比較 ] 語句的設定執行比較。

vbBinaryCompare

0

執行二進位比較。

vbTextCompare

1

執行文字比較。

vbDatabaseCompare

2

Microsoft Office Access 2007 。 根據資料庫中的資訊執行比較。

傳回值

If

InStr 傳回

string1 為零長度

0

string1 是 Null

Null

string2 為零長度

開始

string2 是 Null

Null

找不到 string2

0

string2 是在 string1 中找到的

找到相符專案的位置

開始 > 字串2

0

註解

InStrB 函數會與字串中包含的位元組數據搭配使用。 InStrB 會傳回位元組位置,而不是傳回另一個字串內第一個字串的字元位置。

範例

在表達式中使用 InStr 函數    您可以在任何可以使用表示式的地方使用 InStr 。 例如,如果您要尋找第一期 (的位置 ) 在包含IP位址 (名為IPAddress) 的欄位中,您可以使用 InStr 來尋找,如下所示:

InStr (1,[IPAddress],“”。)

InStr 函數會檢查IPAddress欄位中的每個值,並傳回第一個週期的位置。 因此,如果IP位址的第一部分是10,,函數會傳回值 3。

接著,您可以使用其他函數, 在 InStr 函數輸出上操作,以擷取第一個週期之前的 IP 位址部分,如下所示:

左 ([IPAddress], (InStr (1,[IPAddress],“”。) -1) )

在此範例 中,InStr (1,[IPAddress],“”。) 傳回第一期的位置。 減 1 會決定第一個句點前面有多少個字元,在此情況下是 2。 然後 Left 函數會從 IPAddress 功能變數的左側部分擷取許多字元,並傳回值 10。

在 VBA 程序代碼中使用 InStr    

附註: 下列範例示範如何在 Visual Basic for Applications (VBA) 模組中使用此函數。

此範例使用 InStr 函數傳回另一個字串中第一個出現位置。

Dim SearchString, SearchChar, MyPos
SearchString ="XXpXXpXXPXXP"    ' String to search in.
SearchChar = "P"    ' Search for "P".
' A textual comparison starting at position 4. Returns 6.
MyPos = Instr(4, SearchString, SearchChar, 1)    
' A binary comparison starting at position 1. Returns 9.
MyPos = Instr(1, SearchString, SearchChar, 0)
' Comparison is binary by default
' (last argument is omitted).
MyPos = Instr(SearchString, SearchChar)    ' Returns 9.
MyPos = Instr(1, SearchString, "W")    ' Returns 0.

另請參閱

字串函數及其使用方法

Need more help?

Want more options?

探索訂閱權益、瀏覽訓練課程、瞭解如何保護您的裝置等等。

社群可協助您詢問並回答問題、提供意見反應,以及聆聽來自具有豐富知識的專家意見。

Was this information helpful?

How satisfied are you with the translation quality?
What affected your experience?
By pressing submit, your feedback will be used to improve Microsoft products and services. Your IT admin will be able to collect this data. Privacy Statement.

Thank you for your feedback!

×