【问题标题】:Excel VBA - Extract numeric value in stringExcel VBA - 提取字符串中的数值
【发布时间】:2017-03-14 22:00:30
【问题描述】:

我有多个数据表,其中的一列包含有关各种合同价值的信息。对于每份合同,该列的每个单元格中包含的信息如下所示:

“合约价值为$XX,XXX.XX。”

有时,美元值后面会有额外的文字,如下:

“合约价值为$XX,XXX.XX。有修改合约期限的选项”

我需要编写一个子程序,允许我在该文本字符串中提取美元值并只保留该信息(并且没有任何文本出现在之前和之后)。

我在这里面临的困难是一切都可能发生变化。美元价值永远不会相同,它之前或之后的文字也会发生变化。

到目前为止,我已经能够使用 SPLIT 函数和 $ 作为分隔符成功地保留 $ 符号之后的所有内容。但是,我一直在删除可能跟随美元价值的任何文本时遇到问题。

知道如何继续吗?

感谢您的帮助!

【问题讨论】:

  • 美元值两边的字符串中是否有任何数字?
  • 美元符号后面总有小数点吗?
  • 乔丹:有可能。
  • 约翰·科尔曼:总是。
  • 所有三个建议都有效。谢谢您的意见。你为我节省了大量时间。

标签: excel vba extract


【解决方案1】:

最简单的方法是使用正则表达式:

'Requires a reference to Microsoft VBScript Regular Expressions X.X
Public Function ExtractNumber(inValue As String) As Double
    With New RegExp
        .Pattern = "(\d{1,3},?)+(\.\d{2})?"
        .Global = True
        If .Test(inValue) Then
            ExtractNumber = CDbl(.Execute(inValue)(0))
        End If
    End With
End Function

示例用法:

Sub Example()
    Debug.Print ExtractNumber("The value of the contract is $12,345.67. More text.")
End Sub

【讨论】:

    【解决方案2】:

    VBA 函数val() 有一个很好的属性,它不受数字后面的文本的干扰。所以可能会出现以下情况:

    Function ExtractAmount(data As String) As Variant
        Dim s As String
        s = Split(data, "$")(1) 'part after first dollar sign
        s = Replace(s, ",", "") 'throw away any commas
        ExtractAmount = CCur(Val(s))
    End Function
    

    例如,

    【讨论】:

      【解决方案3】:

      以防万一它更容易 - 您实际上可能不需要潜艇。像这样的公式:

      =VALUE(LEFT(MID(B3,FIND("$",B3)+1,LEN(B3)),FIND(".",B3)-FIND("$",B3)+2))

      适用于本例:

      【讨论】:

        【解决方案4】:

        如果字符串中除了美元值之外没有数字,这将起作用:

        代码

        Sub testingsub()
        
        Dim str As String
        Dim x, p1, p2 As Integer
        
        str = "The value of the contract is $00,000.00. There is an option to modify the duration of the contract"
        p1 = InStr(str, "$")
        
        For x = Len(str) To 1 Step -1
            If IsNumeric(Mid(str, x, 1)) Then
                p2 = x + 1
                Exit For
            End If
        Next x
        
        Debug.Print Mid(str, p1, p2 - p1)
        
        End Sub
        

        结果

        $00,000.00

        【讨论】:

          【解决方案5】:

          如果你上次不打扰

          Function GetMoney(txt As String) As String
              GetMoney = "$" & Split(Split(txt, "$")(1), " ")(0)
          End Function
          

          其他

          Function GetMoney(txt As String) As String
              GetMoney = "$" & Split(Split(txt, "$")(1), " ")(0)
              GetMoney = Left(GetMoney, Len(GetMoney) - 1)
          End Function
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-05-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-09-03
            • 1970-01-01
            • 2016-03-14
            • 1970-01-01
            相关资源
            最近更新 更多