vba - 使用 VBA 从字符串中提取连续数字

标签 vba excel

我编写了一个子程序,它从单元格 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/

相关文章:

arrays - 努力总结我的数组

sql-server - 如何使用 SqlBulkCopy 保持行顺序?

vba - 如何在满足条件时删除Excel中的整行

python - 尝试使用 python 在 xlwt 中设置单元格颜色时丢失属性错误

.net - 如何选择从Excel运行的.NET框架版本?

javascript - excel和javascript的结果公式不同

excel - 从网站列表中抓取数据

特定工作表的 Excel 选择已更改

Excel VBA - 使用 SELECT CASE 但现在需要一个数组

excel - 初始化时从工作表向用户窗体添加图片