通过指定子字符串的第一个和最后一个字符串来提取字符串中的子字符串
问题描述:
我想知道是否有办法通过指定开始的几个字符和结束字符来提取子字符串的字符串。通过指定子字符串的第一个和最后一个字符串来提取字符串中的子字符串
作为一个例子,我在工作簿中的单元格中有类似于问题底部的字符串,并且每个单元格都有一个类似的大字符串。我想提取所有的名字到一个数组中。
“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
答
重新阅读您的问题后编辑我想我没有正确回答它。请详细说明每个单元格中实际包含的内容以及我们正在讨论的单元格数量(1?)。
字符串是字符的串联。在几行写你的字符串并不意味着它实际上改变了。正如你所说的,当你输入chr(10)或者vbLF时,行改变就会发生。我不确定你发布的字符串中哪部分想要提取。假设你想利用一个单元的名称,以及该字符串是在字符串变量[MyString中]举行:
Dim name as string
Dim namestart as integer
Dim nameend as integer
namestart = Instr(Mystring, "c1-mc-")
name = Mid(Mystring, namestart + 1)
nameend = Instr(Mystring, vbLF)
name = Left(name, nameend)
现在的名称将包含您的字符串的名称。测试一下(我没有,你可能需要调整一些小的东西),当你有它时,使用for循环遍历你的单元格,并将名称添加到你想要的数组。
编辑2: 既然你要提取的名称的所有实例在你的,我会把它改成这样:
Dim name as string
Dim namestart as integer
Dim nameend as integer
Dim namearray() as string
Dim i as integer
Do Until Instr(Mystring, "c1-mc-") = 0 'will continue filling the array until Mystrign no longer has any names)
namestart = Instr(Mystring, "c1-mc-")
name = Mid(Mystring, namestart + 1)
nameend = Instr(Mystring, vbLF)
name = Left(name, nameend) 'this gives you a name
Mystring = Mid(Mystring, Instr(Mystring, name)) 'this cuts the original string so it now starts where the name ended.
namearray(i) = name
i = i + 1
Loop
如果你正在做大量的这个,你可能会发现寻找到正规表达式在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感谢您的参考。 –