我想知道是否有一种方法可以通过指定开头的几个字符和结束字符来提取字符串中的子字符串。
作为一个例子,我在工作簿的单元格中的问题的底部有字符串,每个单元格都有一个类似的大字符串。我想将所有名称提取到一个数组中。
“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
答案 0 :(得分: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