2013-03-23 243 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 –

相关问题