在string中查找位置

我想find一个string中的子string的位置,但面临一些问题。 这是代码

Function findPos( Searchval As String, Output As String) As Long Dim pos, i, count As Long pos = InStr(1, content, searchVal, 0) If pos = 0 Then count = 0 Else count = 1 End If If pos > 0 Then For i = 1 To pos If Mid(content, i, 1) = "/" Then count = count + 1 Next i End If findPos=count End Function 

例如:如果输出是“AA / AE_ABC / AE / CD” ,如果我searchVal是“AE”,那么我得到的输出位置为2,这是错误的,因为我应该得到3.我知道代码pos必须修改但不能确定。

如果你只是想findstring的位置,然后使用这个

 Sub Sample() Debug.Print findPos("AE", "AA/AE_ABC/AE/CD") End Sub Function findPos(Searchval As String, Output As String) As Long findPos = InStr(1, Output, Searchval, 0) End Function 

顺便说一下,位置是4而不是3

编辑:如果你正在寻找“/”后面的位置,那么试试这个

 Sub Sample() Debug.Print findPos("AE", "AA/AE_ABC/AE/CD") End Sub Function findPos(Searchval As String, Output As String) As Long Dim MyAr Dim i As Long '~~> Check if output has "/" If InStr(1, Output, "/", 0) Then '~~> Split it and store it in an array MyAr = Split(Output, "/") '~~> Loop through the array to find an exact match For i = LBound(MyAr) To UBound(MyAr) If MyAr(i) = Searchval Then findPos = i + 1 Exit Function End If Next i Else '~~> Check if both Searchval and Output are same If Output = Searchval Then findPos = 1 End If End Function 

像这样的东西应该为你工作,清晰地评论:

 Function findPos(ByVal strFind As String, _ ByVal strContent As String, _ Optional ByVal sDelimiter As String = "/") As Long 'strFind is the substring you're searching for 'strContent is the string you're looking in for strFind 'Be default sDelimiter is '/' but it can be specified as something else Dim varSection As Variant Dim i As Long 'Check if strFind exists in strContent by itself with the delimiter If InStr(1, sDelimiter & strContent & sDelimiter, sDelimiter & strFind & sDelimiter, vbTextCompare) > 0 Then 'It exists, loop through delimited sections of strContent to return the position For Each varSection In Split(strContent, sDelimiter) i = i + 1 'Increase section count If varSection = strFind Then 'Check for match 'Match found, return position and exit for loop findPos = i Exit For End If Next varSection Else 'No match found, return 0 findPos = 0 End If End Function