Pyt*_*hon 3 excel vba excel-vba
我写了一个sub,它从单元格A1中的字符串中提取所有数字,并将结果粘贴到单元格A2中.这循环遍历重复该过程的每一行,直到包含字符串的所有单元格都已完成.
但是,我想只提取连续的数字(超过1位数)
例如:从这个字符串:string-pattern-7 --- 62378250-stringpattern.html我只想提取数字62378250而不是前面的7.
我应该如何改变我的代码才能实现这一目标?
Option Explicit
Function onlyDigits(s As String) As String
' Variables needed (remember to use "option explicit"). '
Dim retval As String ' This is the return string. '
Dim i As Integer ' Counter for character position. '
' Initialise return string to empty '
retval = ""
' For every character in input string, copy digits to '
' return string. '
For i = 1 To Len(s)
If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= "9" Then
retval = retval + Mid(s, i, 1)
End If
Next
' Then return the return string. '
onlyDigits = retval
End Function
Sub extractDigits()
Dim myStr As String
Do While ActiveCell.Value <> Empty
myStr = onlyDigits(ActiveCell.Value)
ActiveCell(1, 2).Value = myStr
ActiveCell.Offset(1, 0).Select
Loop
End Sub
Run Code Online (Sandbox Code Playgroud)
如果您只有一个序列,请认为这应该这样做
Function onlyDigits(v As Variant) As String
With CreateObject("vbscript.regexp")
.Pattern = "\d{2,}"
If .Test(v) Then onlyDigits = .Execute(v)(0)
End With
End Function
Run Code Online (Sandbox Code Playgroud)