我编写了一个子程序,它从单元格 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
最佳答案
如果你只有一个序列,这应该可以做到
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
关于vba - 使用 VBA 从字符串中提取连续数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42822501/