【发布时间】:2015-06-19 16:36:20
【问题描述】:
我想知道是否有一种方法可以通过指定开始的几个字符和结束字符来从字符串中提取子字符串。
作为一个例子,我在工作簿的一个单元格中的问题底部有一个字符串,每个单元格都有一个类似的大字符串。我想将所有名称提取到一个数组中。
“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 中查看正则表达式。它允许根据标准对字符串进行各种切片和切块。这是an excellent post 的主题。
-
你给我看的字符串是这样的:“Str: 1/2/1End : 1/2/2Name: cl-mc-23223322Name: c1-mc-dddssdaInfo: alot of detailName: c1- asa-dddssdatask: asdfName: c1-mc-xd132eds" 字符串中没有“输入”。也许你的意思是 "Str: 1/2/1" & vbLF & "End : 1/2/2" & vbLF & "Name: cl-mc-23223322" & vbLF...
-
@Byron 感谢您的参考。