如何找到一个在数字周围包含括号的单元格-例如(1)

时间:2019-01-02 20:42:17

标签: excel vba excel-vba user-defined-functions

我正在使用的公式是:

=IF(SUM(COUNTIF(K6,"*"&{"current","(1)"}&"*")),"within 5 minutes",
IF(SUM(COUNTIF(K6,"*"&{"current","(2)"}&"*")),"within 10 minutes",
IF(SUM(COUNTIF(K6,"*"&{"current","(3)"}&"*")),"within 15 minutes",
IF(SUM(COUNTIF(K6,"*"&{"current","(4)"}&"*")),"within 20 minutes",
IF(SUM(COUNTIF(K6,"*"&{"current","(5)"}&"*")),"within 25 minutes",
IF(SUM(COUNTIF(K6,"*"&{"current","(6)"}&"*")),"within 30 minutes"))))))

输出将提取同时包含current1 / 2 / 3等的任何单元格。

我需要它仅提取包含current(1) / (2) / (3)等的单元格。


希望有一种简单的方法可以确保公式中包含括号!


以下是预期结果的屏幕截图示例: enter image description here

2 个答案:

答案 0 :(得分:2)

如果您真的不想遵循@Andreas的建议(这是另一种表达“为什么我没有想到这一点”的方法),请尝试:

=IFERROR(IF(FIND("current",A3)>0,CONCATENATE("within ", CHOOSE(VALUE(MID(A3,FIND("(",A3)+1,1)),5,10,15,20,25,30), " minutes"),),FALSE)

注意:它忽略右括号,因此this cell contains current and (1不会返回“ FALSE”

答案 1 :(得分:2)

如果VBA和UDF可以,那么我建议您使用正则表达式。

打开VBA编辑器(ALT + F11)并添加一个模块。

粘贴以下代码,然后将Excel工作簿另存为宏激活工作簿(xlsm)。

Function Regex(Cell)
    Dim RE As Object

    Set RE = CreateObject("vbscript.regexp")

    RE.Pattern = ".*(current and \(\d+\))"
    ' or if you want to match optional ()
    'RE.Pattern = ".*(current and \(?\d+\)?)"
    RE.Global = True
    RE.IgnoreCase = True
    Set Matches = RE.Execute(Cell)

    If Matches.Count <> 0 Then
        Regex = Matches.Item(0).submatches.Item(0)
    End If

End Function

将其用作公式,例如:

=Regex(A1)

它将返回正在寻找的部分current and [number]

代码的返回当然可以是您想要的任何内容。
但是我不明白您的问题的逻辑,即为什么我返回它正在寻找的内容


我现在明白了。

这将按预期返回输出。

Function Regex(Cell)
    Dim RE As Object

    Set RE = CreateObject("vbscript.regexp")

    RE.Pattern = ".*current and \((\d+)\)"
    ' or if you want to match optional ()
    'RE.Pattern = ".*current and \(?(\d+)\)?"
    RE.Global = True
    RE.IgnoreCase = True
    Set Matches = RE.Execute(Cell)

    If Matches.Count <> 0 Then
        Regex = "within " & Matches.Item(0).submatches.Item(0)*5 & " minutes"
    Else
        Regex = "False"
    End If

End Function

它将捕获的数字乘以5得到分钟数。
如果未找到任何内容,则返回False

VBA和regex通常意味着工作表中的代码更易于维护和调试。


为了使它对current(number)的字符串作出反应,然后使用以下代码:

Function Regex(Cell)
    Dim RE As Object

    Set RE = CreateObject("vbscript.regexp")

    RE.Pattern = ".*current.*?\((\d+)\)"
    RE.Global = True
    RE.IgnoreCase = True
    Set Matches = RE.Execute(Cell)

    If Matches.Count <> 0 Then
        Regex = "within " & Matches.Item(0).submatches.Item(0)*5 & " minutes"
    Else
        Regex = "False"
    End If

End Function

此代码将查找[anything] current [anything] ([number])