前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >VBA代码库08:获取字符串中指定位置的子字符串

VBA代码库08:获取字符串中指定位置的子字符串

作者头像
fanjy
发布2019-09-19 17:20:42
3.3K0
发布2019-09-19 17:20:42
举报
文章被收录于专栏:完美Excel

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

下面是代码的图片版:

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-09-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 完美Excel 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档