Excel 2010:删除从文本到列的单元格的子string

我有一个电子表格,它有一个在其单元格中有可变数据的列。 此列中的示例单元格具有以下内容。

P5V010000167908-PBD-12300026-01,P5V010000167904-PBD-12300026-01,P5V010000167906-PBD-12300026-01,P5V000000581894-UNDEFINED,P5V000000581895-UNDEFINED,P5V000000581896-

我想删除每个P5V号码(例如,P5V010000167908,P5V010000167904,P5V010000167906等),并将它们放置在本列右侧自己的列中。

P5V编号始终以P5V开头,长度始终为15个字符。 我怎么能只有P5V数字的文字列? 有任何想法吗?

谢谢安迪

您可以使用两个“查找/replace”(Text / Replaces),然后是“文本到列”(Text-to-Columns)

  1. 用空格replace-*,
  2. replace-与空白
  3. 使用文本到列使用空格分隔符拆分

当我用macros录像机做这个,并清理一下,我得到:

 Sub Macro2() With ActiveSheet.Columns("A:A") .Replace What:="-*,", Replacement:="", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False .Replace What:="-", Replacement:="", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False .TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _ TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, _ Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _ :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1)), _ TrailingMinusNumbers:=True End With End Sub 

你可以创build下面的新的UDF(用户定义函数),只需将其插入到VBA模块中,然后在string右侧的单元格中使用它,并增加'n'参数。
例如,如果string在单元格C4中,则D4的公式将为=ExtractP5V($C$4; 1) ,则E4的公式将为=ExtractP5V($C$4; 2)等等。

 Function ExtractP5V(str, n) As String Dim curStart As Integer curStart = 1 Dim i As Integer For i = 1 To n Step 1 Dim nextP5VPos As Integer nextP5VPos = InStr(curStart, str, "P5V") If nextP5VPos = 0 Then ExtractP5V = "-" Exit Function End If If i = n Then ExtractP5V = Mid(str, nextP5VPos, 15) Exit Function End If curStart = nextP5VPos + 1 Next i End Function 

希望有所帮助 – 顺便说一句:代码是不是超级干净… 🙂