在字符串中的短划线两侧返回数值?

时间:2013-09-11 18:55:38

标签: string vba character

有没有人知道如何只在字符串的短划线两侧立即返回数值?

例如,假设我们有以下字符串“Text,2-78,88-100,101”。我正在寻找一种识别短划线的方法,然后返回其中一个数字(左或右)。

最后,我想查看一个给定的数字,比如75,是否属于字符串中指出的任何范围。理想情况下,它会看到75落在“2-78”之内。

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:1)

转到工具 - >参考,然后选中“Microsoft VBScript正则表达式5.5”。然后你可以做这样的事情。 (我知道这不是好代码,但它的想法是......)此外,它找到所有# - #模式并打印所有这些的左或右数字(基于布尔“左”是否为是真是假。

Dim str, res As String
str = "Text, 2-78, 88-100, 101"
Dim left As Boolean
left = False

Dim re1 As New RegExp
re1.Pattern = "\d+-\d+"
re1.Global = True

Dim m, n As Match
For Each m In re1.Execute(str)
    Dim re2 As New RegExp
    re2.Global = False

    If left Then
        re2.Pattern = "\d+"
    Else
        re2.Pattern = "-\d+"
    End If

    For Each n In re2.Execute(m.Value)
        res = n.Value
        If Not left Then
            res = Mid(res, 2, Len(str))
        End If
    Next
    MsgBox res
Next

答案 1 :(得分:0)

您可以使用VBA以多种方式执行此操作。使用Split()函数转换为数组,首先使用逗号作为分隔符然后使用破折号可能是一种方法。

那就是说,如果你想用excel快速而肮脏的方式来做这件事(你可以从中录制一个宏),这就是你能做的。

将目标字符串粘贴到单元格中。 使用逗号作为分隔符,在其上运行Text to Columns。 将您现有的行和粘贴转置复制到新工作表上。 在转置列上再次运行Text to Columns,这次使用短划线作为分隔符。 您现在拥有数字的并排列,您可以根据需要与目标值进行比较。

您可能需要在某处使用Trim()函数来删除空格,但希望文本到列会留下数字而不是文本编号。

答案 2 :(得分:0)

最终,我认为你可以通过很多方式来解决这类问题。它看起来是尝试使用RegExp的好方法。 RegExp不是我的专长,但我喜欢尝试使用它来回答SO上的问题。此代码已针对您的示例数据进行了测试,并且运行正常。

这样的事情,假设你的文本在单元格A1中,并且你正在测试类似75的值,这也会在匹配集合中捕获字符串中的单个数字:

Sub TestRegExp
Dim m As Match
Dim testValue As Long
Dim rangeArray As Variant

testValue = 75  'or whatever value you're trying to find

pattern = "[\d]+[-][\d]+\b|[\d]+"
Set re = New RegExp

re.pattern = pattern
re.Global = True
re.IgnoreCase = True 'doesn't really matter since you're looking for numbers

Set allMatches = re.Execute([A1])

For Each m In allMatches

    rangeArray = Split(m, "-")
    Select Case UBound(rangeArray)
        Case 0
            If testValue = rangeArray(0) Then
                msg = testValue & " = " & m
            Else:
                msg = testValue & " NOT " & m
            End If
        Case 1
            If testValue >= CLng(rangeArray(0)) And testValue <= CLng(rangeArray(1)) Then
                msg = testValue & " is within range: " & m
            Else:
                msg = testValue & " is not within range: " & m
            End If
        Case Else
    End Select

    MsgBox msg, vbInformation


Next


End Sub