VBA代码库08:获取字符串中指定位置的子字符串
- 2019 年 10 月 5 日
- 筆記
excelperfect
下面的自定义函数:ExtractString函数,来源于《VBA Developer’s Handbook》,对于分析字符串来说,是一个很有用的函数。
ExtractString函数可以根据一个或多个分隔符,取出字符串中由这些分隔符分开的指定位置的子字符串。
ExtractString函数代码如下:
'指定默认的分隔符
'可以指定多个分隔符
'可以根据实际需要进行修改
ConstsDelimiter = ","
'参数strIn:指定的字符串
'参数iPiece:指定要提取的子字符串的位置
'参数strDelimiter:默认的分隔符
Function ExtractString(ByVal strIn As String, _
ByVal iPiece As Integer, _
Optional ByVal strDelimiter As String = sDelimiter) As String
'声明变量
Dim iPos As Integer
Dim iLastPos As Integer
Dim iLoop As Integer
Dim iPos1 As Integer
'指定初始值
iPos = 0
iLastPos = 0
iLoop = iPiece
'如果不止一个分隔符,则使用TranslateString函数
'将字符串中所有的分隔符替换成第一个分隔符
If Len(strDelimiter) > 1 Then
strIn = TranslateString(strIn, _
strDelimiter, Left$(strDelimiter, 1))
End If
'循环,获取子字符串的位置
Do While iLoop > 0
iLastPos = iPos
iPos1 = InStr(iPos + 1, strIn,Left$(strDelimiter, 1))
If iPos1 > 0 Then
iPos = iPos1
iLoop = iLoop – 1
Else
iPos = Len(strIn) + 1
Exit Do
End If
Loop
'判断在指定位置是否存在子字符串
If (iPos1 = 0) And (iLoop <> iPiece) And (iLoop > 1) Then
ExtractString = ""
Else
'存在,则提取子字符串
ExtractString = Mid$(strIn, _
iLastPos + 1, iPos – iLastPos – 1)
End If
End Function
在代码中,使用了《VBA代码库07.功能强大的字符替换函数》介绍的TranslateString函数,将字符串中的分隔符全部替换为分隔符列表中的第一个分隔符。因此,必须将TranslateString函数代码放置在与本代码相同的工作簿中。
代码:
Do While iLoop > 0
iLastPos = iPos
iPos1 = InStr(iPos + 1, strIn,Left$(strDelimiter, 1))
If iPos1 > 0 Then
iPos = iPos1
iLoop = iLoop – 1
Else
iPos = Len(strIn) + 1
Exit Do
End If
Loop
遍历字符串,找到指定位置的子字符串在字符串中开始位置(之前的分隔符位置,即变量iLastPos的值)和结束的位置(之后的分隔符位置,即变量iPos的值)。
如果查找分隔符失败,则iPos1的值为0,退出循环。
代码:
If (iPos1 = 0) And (iLoop <> iPiece) And (iLoop > 1) Then
满足这3个条件,表明在指定位置没有找到子字符串,返回空字符串。
应用示例
示例1:获取字符串中的多个子字符串
下面的代码提取字符串中的水果名称:
Sub test()
Dim i As Integer
Dim strSubText As String
Dim strSourceText As String
strSourceText = "水果=苹果,香蕉,菠萝"
i = 2
Do While True
strSubText = ExtractString(strSourceText, i, "=,")
If Len(strSubText) = 0 Then
Exit Do
End If
Debug.Print strSubText
i = i + 1
Loop
End Sub
运行效果如下图1所示。

图1
示例2:在公式中使用来提取指定位置的子字符串
如下图2所示,演示了在公式中使用ExtractString函数的几种情形。

图2
下面是代码的图片版:
