2015-06-19 70 views
2

我想知道是否有办法通过指定开始的几个字符和结束字符来提取子字符串的字符串。通过指定子字符串的第一个和最后一个字符串来提取字符串中的子字符串

作为一个例子,我在工作簿中的单元格中有类似于问题底部的字符串,并且每个单元格都有一个类似的大字符串。我想提取所有的名字到一个数组中。

“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

如果你正在做大量的这个,你可能会发现寻找到正规表达式在VBA中的使用。它允许根据标准对字符串进行各种切片和切块。这是[一个优秀的职位](http://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops)上话题。 –

+0

您向我展示的字符串是:“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 ... –

+0

@Byron感谢您的参考。 –

回答

0

重新阅读您的问题后编辑我想我没有正确回答它。请详细说明每个单元格中实际包含的内容以及我们正在讨论的单元格数量(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 
+0

我在我的问题中发布的字符串是描述事件的列的单元格值。可以有大约4000-5000行具有相同的字段。 在我的问题中,您可以看到名称I.E“c1-mc-23223322”等4个实例。我想要在数组中提取所有名称。 您上面发布的代码,我如何使用它在单元格值上运行多次? – Tan12

+0

@Byron谢谢你,我也会看看正则表达式 – Tan12

+0

我的编辑能帮助你吗?现在它应该取得单元格中的所有名称(我还没有对它进行测试,所以有一个可能性就是要将+1添加到字符位置,例如,使用debug.print来确定添加的内容什么是剪切。) –

相关问题