我有一个可变文本字段坐在其中包含下面的单元格A1:
文本; #NUMBER; #Text; #NUMBER
- 这种格式可以不断重复,但图案总是文字; #NUMBER。
- 中的数字可从1位到n位变化(极限7)
例:
原始值
MyName;#123;#YourName;#3456;#HisName;#78
必需值:
123, 3456, 78
本场是从我的理解Excel公式太多变量。
我尝试使用正则表达式 ,但我是一个初学者,当谈到编码。 如果你能打破一些解释文本的代码,这将是大加赞赏。
我曾尝试下面的一些建议和他们很好地工作。 还有一个问题。
现在,我可以从文本分裂的数字,是有什么办法可以利用下面的代码并添加另一个层,在那里我们的数字分成X细胞。
例如:当我们运行的功能,如果我们在同一个小区获得1234,567,该功能将使1234在单元格B2,在小区C2 567。 这将不断更新的同一行中的所有单元格,直到字符串已用尽所有正在从功能检索到的数字。
谢谢
这是约翰·科尔曼的建议的方法:
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
如果模式是固定的,数字的位置不会改变,你可以假设数字将设在字符串中甚至地方。 这意味着,在对源串分割的阵列结果,则可以使用所得阵列的奇数索引。 例如,在此字符串“文本;# 数量 ; #Text;# 号码 ”数组索引1,3将是数字(“文本(0);# 号(1); #Text(2);# 号(3) “)。 我觉得这个方法更容易,更安全,使用如果模式确实是固定的,因为它避免了需要验证的数据类型。
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)
其他反应都没有,似乎采取提供的参数考虑在内,所以我kludged一起真正的正则表达式的解决方案。
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
使用正则表达式选项Replace
Sub Test()
Debug.Print StrOut("MyName;#123;#YourName;#3456;#HisName;#78")
End Sub
功能
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