用于删除字符串中第一个数字前的任何字符以及点/分号后的任何字符

时间:2014-11-04 07:32:08

标签: excel excel-vba excel-formula vba

如何增强此功能以排除在字符串中的第一个数字和之后的任何字符之前删除任何字符。要么 : ?例如:

GigabitEthernet0/3.210 --> 0/3  
Serial6/2:0.100 --> 6/2  
Serial6/6:0 --> 6/6 

Function: =REPLACE($A2,1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},$A2&"0123456789"))-1,"")

2 个答案:

答案 0 :(得分:1)

您可以使用已有的功能获取该功能,并使用MID功能代替替换:

=MID(
     $A1,
     MIN(FIND({0,1,2,3,4,5,6,7,8,9},$A1&"0123456789")),
     MIN(FIND({":","."},$A1&".:"))-MIN(FIND({0,1,2,3,4,5,6,7,8,9},$A1&"0123456789"))
)

答案 1 :(得分:0)

我会用正则表达式来解决这个问题 - 如果需要的话,它将允许规则更灵活。

E.g。使用以下vba代码公开REGEXP:

Function RegExp(ByVal repattern As String, ByVal value As String, Optional occurrence = 1)
' does a regular expression search for "repattern" in string "value"
' returns the match
'  or "" if not found

  RegExp = ""
  Dim RegEx As Object, RegMatchCollection As Object, RegMatch As Object
  ' create the RegExp Object with late binding
  Set RegEx = CreateObject("vbscript.regexp")
  With RegEx
    .Global = True      'look for global matches
    .Pattern = repattern
  End With
  counter = 1
  Set RegMatchCollection = RegEx.Execute(value)
  For Each RegMatch In RegMatchCollection
    If counter = occurrence Then
      RegExp = RegMatch.value
      Exit For
    Else
      counter = counter + 1
    End If
  Next
  Set RegMatchCollection = Nothing
  Set RegEx = Nothing
End Function

然后,您可以在工作表上使用公式,例如=RegExp("[0-9][^\.:]*",A1)