Excel VBA – 在string中提取数字值

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

“合同的价值是$ XX,XXX.XX”。

有时,在美元价值之后会有额外的文字,如下所示:

“合同的价值是$ XX,XXX.XX。可以select修改合同期限”

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

我在这里面临的困难是,一切都是可以改变的。 美元价值是不一样的,它之前或之后的文本也会改变。

到目前为止,我已经能够成功地保存$符号后面的所有内容,使用SPLIT函数和$作为分隔符。 然而,我仍然有问题删除任何可能跟随美元价值的文字。

任何想法如何我可以继续?

感谢您的帮助!

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 

例如,

在这里输入图像说明

以防万一它更容易 – 你可能不需要一个子。 像这样的一个公式:

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

适用于这个例子:

在这里输入图像说明

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

 'Requires a reference to Microsoft VBScript Regular Expressions XX 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 

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

 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

如果你不打扰上一段时间

 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