我想知道是否有办法通过指定开始的几个字符和结束字符来提取子字符串的字符串。通过指定子字符串的第一个和最后一个字符串来提取字符串中的子字符串
作为一个例子,我在工作簿中的单元格中有类似于问题底部的字符串,并且每个单元格都有一个类似的大字符串。我想提取所有的名字到一个数组中。
“c1-mc-”将始终是名称的前缀。我希望我可以使用一个函数,在该函数中我可以指定对于以“c1-mc”开头并以vbLf(enter)结尾的每个子串,提取这些子串。 我认为Instr()和Split()可以帮助但不知道如何继续。
"Str: 1/2/1
End : 1/2/2
Name: cl-mc-23223322
Name: c1-mc-dddssda
Info: alot of detail
Name: c1-asa-dddssda
task: asdf
Name: c1-mc-xd132eds"
<the code which works>
For Each rng1 In table1.DataBodyRange.Columns(8).Cells
MyString = rng1.Value
Do Until InStr(MyString, "c1-mc") = 0
namestart = InStr(MyString, "c1-mc")
name = Mid(MyString, namestart)
nameend = InStr(name, vbLf) - 1
name = Left(name, nameend) 'this gives you a name
namestart = InStr(name, "c1-mc")
name = Mid(name, namestart)
nameend = InStr(name, " ") - 1
If (nameend = -1) Then
nameend = Len(name)
End If
name = Left(name, nameend) ' gives you name incase there are no next lines
MyString = Replace(MyString, name, "") 'this cuts the original string so it now starts where the name ended.
MsgBox name
i = i + 1
Loop
Next
如果你正在做大量的这个,你可能会发现寻找到正规表达式在VBA中的使用。它允许根据标准对字符串进行各种切片和切块。这是[一个优秀的职位](http://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops)上话题。 –
您向我展示的字符串是:“Str:1/2/1End:1/2/2Name:cl-mc-23223322Name:c1-mc-dddssdaInfo:很多详细信息名称:c1-asa-dddssdatask:asdfName:c1 -mc-xd132eds“字符串中没有”进入“。也许你的意思是“Str:1/2/1”&vbLF&“End:1/2/2”&vbLF&“Name:cl-mc-23223322”&vbLF ... –
@Byron感谢您的参考。 –