2013-03-23 242 views

回答

269

使用Instr功能

Dim pos As Integer 

pos = InStr("find the comma, in the string", ",") 

將在POS返回15

如果沒有找到則返回0

如果你需要找到一個Excel公式可以用逗號=FIND(",";A1)功能。

請注意,如果您想使用Instr來查找字符串的位置不區分大小寫,請使用Instr的第三個參數,併爲其指定const vbTextCompare(或者對於頑固派只有1)。

Dim posOf_A As Integer 

posOf_A = InStr(1, "find the comma, in the string", "A", vbTextCompare) 

會給你,你在我聯繫的規格說明來指定在這種情況下,起始位置的14

的值。注:如果比較是必需的啓動參數中指定。

+2

但是如果找到的字符串在位置0呢?你如何區分「找到索引0」和「找不到(0)」? – gEdringer

+6

@gEdringer。當要找到的字符串在開始時,它返回1. – rene

18

還有一個InStrRev函數,它執行相同類型的事情,但是從文本的末尾開始搜索到開頭。

每@劉若英的回答......

Dim pos As Integer 
pos = InStrRev("find the comma, in the string", ",") 

...還是會回到15〜POS機,但如果字符串搜索字符串的不止一個,比如單詞 「the」,則:

Dim pos As Integer 
pos = InStrRev("find the comma, in the string", "the") 

...會回到20〜POS機,而不是6

15

大廈劉若英的回答,你也可以寫返回爲TRUE,如果子存在,或FALSE如果WASN功能't:

Public Function Contains(strBaseString As String, strSearchTerm As String) As Boolean 
'Purpose: Returns TRUE if one string exists within another 
On Error GoTo ErrorMessage 
    Contains = InStr(strBaseString, strSearchTerm) 
Exit Function 
ErrorMessage: 
MsgBox "The database has generated an error. Please contact the database administrator, quoting the following error message: '" & Err.Description & "'", vbCritical, "Database Error" 
End 
End Function 
+2

我們期望在這個函數中出現什麼樣的數據庫錯誤?錯誤陷阱和錯誤消息似乎完全沒有意義。 –

+7

@RoobieNuby這只是我的默認錯誤處理。我把它放在我所有的功能上,因爲如果出現問題,我希望工作人員給我打電話,而不是自己嘗試修復它。 – BFWebAdmin

38

您還可以使用特殊的字like

Public Sub Search() 
    If "My Big String with, in the middle" Like "*,*" Then 
    Debug.Print ("Found ','") 
    End If 
End Sub 
+2

鏈接到模式格式https://msdn.microsoft.com/en-us/library/swf8kaxw.aspx?f=255&MSPPError=-2147217396 –

相關問題