【问题标题】:Extract first two digits that comes after some string in Excel提取Excel中某个字符串之后的前两位数字
【发布时间】:2018-03-13 20:47:48
【问题描述】:

我有一行这样的值,如何将文本“ABCD”之后的前两位数字提取到另一个单元格、任何公式或 vba?中间可能有几个字符,有时甚至没有。

  • ABCD 10 sadkf sdfas
  • ABCD-20sdf asdf
  • ABCD 40
  • ABCD50 asdf

【问题讨论】:

    标签: vba excel excel-formula


    【解决方案1】:

    您可以使用工作表公式来做到这一点。不需要 VBA。

    假设您不需要测试是否存在两位数:

    =MID(A1,MIN(FIND({1,2,3,4,5,6,7,8,9,0},A1&"1234567890")),2)
    

    如果需要测试两位数的存在,可以试试:

    =IF(ISNUMBER(-RIGHT(MID(A1,MIN(FIND({1,2,3,4,5,6,7,8,9,0},A1&"1234567890")),2),1)),MID(A1,MIN(FIND({1,2,3,4,5,6,7,8,9,0},A1&"1234567890")),2),"Invalid")
    

    【讨论】:

      【解决方案2】:

      一般来说,在 StackOverflow 中显示一些代码总是一个好主意。因此,你表明你已经尝试了一些东西,并给出了一些答案的方向。

      关于前两位数字的提取,有很多方法可以做到这一点。从 RegEx 开始,以简单的字符循环结束并检查每个字符。

      这是循环选项:

      Public Function ExtractTwoDigits(inputString As String) As Long
      
          Application.Volatile
      
          Dim cnt     As Long
          Dim curChar As String
      
          For cnt = 1 To Len(inputString)
              curChar = Mid(inputString, cnt, 1)
              If IsNumeric(curChar) Then
                  If Len(ExtractTwoDigits) Then
                      ExtractTwoDigits = ExtractTwoDigits & curChar
                      Exit Function
                  Else
                      ExtractTwoDigits = curChar
                  End If
              End If
          Next cnt
      
          ExtractTwoDigits = -1
      
      End Function
      
      • Application.Volatile 确保每次都重新计算公式;
      • 如果inputString 中不存在两位数,则-1 是答案;
      • IsNumeric检查里面的字符串是否为数字;
      • 作为进一步的步骤,您可以尝试使函数更健壮,根据您输入的参数提取第一个 1345 数字。类似这样的=ExtractTwoDigits("tarato123ra2",4),返回1232

      【讨论】:

        【解决方案3】:

        正则表达式版本:

        Public Function GetFirstTwoNumbers(ByVal strInput As String) As Integer
        Dim reg As New RegExp, matches As MatchCollection
        
        With reg
            .Global = True
            .Pattern = "(\d{2})"
        End With
        
        Set matches = reg.Execute(strInput)
        If matches.Count > 0 Then
            GetFirstTwoNumbers = matches(0)
        Else
            GetFirstTwoNumbers = -1
        End If
        End Function
        

        你必须在 extras->references 下启用Microsoft Regular Expressions 5.5。模式(\d{2}) 匹配 2 位数字,返回值为数字,如果不存在 -1。

        注意:它只提取2个连续的数字。

        如果将此函数放入模块中,则可以像普通公式一样使用它。

        Here 一个进入正则表达式的好网站。

        【讨论】:

          猜你喜欢
          • 2018-06-27
          • 2018-08-21
          • 2014-11-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多