如何从字符串中查找数字? [英] How to find numbers from a string?

查看:129
本文介绍了如何从字符串中查找数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从字符串中找到数字。如何从VBA Excel中的字符串中找到数字?

解决方案

假设你的意思是你想要的非数字被删除,你应该能够使用如下的东西:

 函数onlyDigits(s As String)As String 
'需要变量(记住使用显式选项)。 '
Dim retval As String'这是返回字符串。 '
Dim i As Integer'字符位置的计数器。 '

'初始化返回字符串为空'
retval =

'对于输入字符串中的每个字符,将数字复制到'
'返回串。 '
对于i = 1到Len(s)
如果Mid(s,i,1)> =0和Mid(s,i,1)< =9然后
retval = retval + Mid(s,i,1)
End If
Next

'然后返回返回字符串。 '
onlyDigits = retval
结束函数

通过以下方式调用:


  Dim myStr as String 
myStr = onlyDigits(3d1fgd4g1dg5d9gdg)
MsgBox(myStr)

将给您一个包含以下内容的对话框:

这些前两行显示了如何将它存储到任意的位置,而$字符串变量,可以根据需要进行。


I need to find numbers from a string. How does one find numbers from a string in VBA Excel?

解决方案

Assuming you mean you want the non-numbers stripped out, you should be able to use something like:

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

Calling this with:

Dim myStr as String
myStr = onlyDigits ("3d1fgd4g1dg5d9gdg")
MsgBox (myStr)

will give you a dialog box containing:

314159

and those first two lines show how you can store it into an arbitrary string variable, to do with as you wish.

这篇关于如何从字符串中查找数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆