Excel UDF用于捕获字符中的数字

我有一个坐在单元格A1中的variables文本字段,其中包含以下内容:

文本; #NUMBER; #Text; #NUMBER

  • 这种格式可以不断重复,但模式始终是文本;#编号。
  • 数字可以从1位数到n位数(限制7)

例:

原始值

MyName;#123;#YourName;#3456;#HisName;#78

所需值:

123, 3456, 78

从我的理解来看,这个领域对于excel公式来说太可变了。

我尝试使用正则expression式,但我是一个初学者,当谈到编码。 如果你可以用一些解释文本分解代码,那将是非常感谢。

我已经尝试了下面的一些build议,他们完美的工作。 还有一个问题。

现在我可以从文本中拆分数字了,有什么方法可以利用下面的代码并添加另一个图层,在这里我们将数字拆分成x个单元格。

例如:一旦我们运行这个函数,如果我们得到1234,567在同一个单元格中,那么函数会把1234放在B2单元格中,567单元格放在C2单元格中。 这将不断更新同一行中的所有单元格,直到string耗尽了从函数中检索的所有数字。

谢谢

这是约翰·科尔曼build议的方法:

 Public Function GetTheNumbers(st As String) As String ary = Split(st, ";#") GetTheNumbers = "" For Each a In ary If IsNumeric(a) Then If GetTheNumbers = "" Then GetTheNumbers = a Else GetTheNumbers = GetTheNumbers & ", " & a End If End If Next a End Function 

如果模式是固定的,并且数字的位置永远不会改变,您可以假设数字将位于string的偶数位置。 这意味着在源string拆分的数组结果中,可以使用结果数组的奇数索引。 例如,在这个string“Text# Number #Text# Number ”数组索引1,3中是数字(“Text(0);# Number(1) ; #Text(2);# Number(3) “)。 如果模式确实是固定的,我认为这个方法更容易和更安全,因为它避免了validation数据types的需要。

 Public Function GetNums(src As String) As String Dim arr Dim i As Integer Dim result As String arr = Split(src, ";#") ' Split the string to an array. result = "" For i = 1 To UBound(arr) Step 2 ' Loop through the array, starting with the second item, and skipping one item (using Step 2). result = result & arr(i) & ", " Next If Len(result) > 2 Then GetNums = Left(result, Len(result) - 2) ' Remove the extra ", " at the end of the the result string. Else GetNums = "" End If End Function 

数字可以从1位数到n位数( 限制7

其他答案似乎没有考虑到提供的参数,所以我拼凑了一个真正的正则expression式解决scheme。

 Option Explicit Option Base 0 '<~~this is the default but I've included it because it has to be 0 Function numsOnly(str As String, _ Optional delim As String = ", ") Dim n As Long, nums() As Variant Static rgx As Object, cmat As Object 'with rgx as static, it only has to be created once; beneficial when filling a long column with this UDF If rgx Is Nothing Then Set rgx = CreateObject("VBScript.RegExp") End If numsOnly = vbNullString With rgx .Global = True .MultiLine = False .Pattern = "[0-9]{1,7}" If .Test(str) Then Set cmat = .Execute(str) 'resize the nums array to accept the matches ReDim nums(cmat.Count - 1) 'populate the nums array with the matches For n = LBound(nums) To UBound(nums) nums(n) = cmat.Item(n) Next n 'convert the nums array to a delimited string numsOnly = Join(nums, delim) End If End With End Function 

numsOnly

使用Replace Regexp选项

 Sub Test() Debug.Print StrOut("MyName;#123;#YourName;#3456;#HisName;#78") End Sub 

function

 Option Explicit Function StrOut(strIn As String) As String Dim objRegex As Object Set objRegex = CreateObject("vbscript.regexp") With objRegex .Pattern = "(^|.+?)(\d{1,7})" .Global = True If .Test(strIn) Then StrOut = .Replace(strIn, "$2, ") StrOut = Left$(StrOut, Len(StrOut) - 2) Else StrOut = "Nothing" End If End With End Function