VBA如何查字符字符串中某个字符的位置instr()函数
Instr()
函数返回字符或字符串在另⼀个字符串中第⼀次出现的位置.
表达式 Instr([start, ] strToBeSearched, strSearchFor [, compare])
允许数据类型: Start为搜索的起始值,strToBeSearched接受搜索的字符串 strSearchFor要搜索的字符pare⽐较⽅式(详细见ASP常数)
实例: <%
strText = "This is a test!!"
pos = Instr(strText, "a")
response.write pos
%>
返回结果: 9
备注:如果接受搜索的字符串中没有要搜索的字符串,则返回结果为0。
实例:
<%
strText = "This is a test!!"
pos = Instr(strText, "b")
response.write pos
%>
返回结果: 0
⾃定义函数1,获取单⼀种类字符的所有位置,或第n个的位置。
=GetPosition(【单元格】,【查字符】,【指定第n个,可省略】)
Function GetPosition(Cell, Txt, Optional k = 0)请写出至少5个字符串函数
n = InStr(Cell, Txt)
p = n
c = 1
Do
If c = k Then GetPosition = n: Exit Function
n = InStr(n + 1, Cell, Txt)
If n = 0 Then Exit Do
c = c + 1
p = p & "," & n
Loop
GetPosition = p
End Function
如何查字符字符串中某个字符的所有位置,⽐如字符串“a<12345>bc<12345>ef<1>”
Sub Test()
istr = "a<12345>bc<12345>ef<1>"
Dim arr1()
Dim arr2()
n = 0
iloc = 0
Do
iloc = InStr(iloc + 1, istr, "<")
If iloc > 0 Then
ReDim Preserve arr1(0 To n)
arr1(n) = iloc
n = n + 1
End If
Loop Until iloc = 0
MsgBox "字符<;出现的位置:" & Join(arr1, ",")
n = 0
iloc = 0
Do
iloc = InStr(iloc + 1, istr, ">")
If iloc > 0 Then
ReDim Preserve arr2(0 To n)
arr2(n) = iloc
n = n + 1
End If
Loop Until iloc = 0
MsgBox "字符>出现的位置:" & Join(arr2, ",")
End Sub
⾃定义函数2,获取⼀对(两种字符)的所有位置+B5,或第n对的位置。
=GetPairPosition(【单元格】,【查字符1】,【查字符2】,【指定第n对,可省略】) Function GetPairPosition(Cell, Txt1, Txt2, Optional k = 0)
n1 = InStr(Cell, Txt1)
n2 = InStr(Cell, Txt2)
c = 1
p = n1 & "-" & n2
Do
If c = k Then GetPairPosition = n1 & "-" & n2: Exit Function
n1 = InStr(n1 + 1, Cell, Txt1)
n2 = InStr(n2 + 1, Cell, Txt2)
If n1 * n2 = 0 Then Exit Do
c = c + 1
p = p & "," & n1 & "-" & n2
Loop
GetPairPosition = p
End Function
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论