使用 VBA 从字符串中获取整数值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12870379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Integer value from String using VBA
提问by user1742862
I'm trying to automate a script using QTP and SAP.
我正在尝试使用 QTP 和 SAP 自动化脚本。
In SAP an order is generated with Document number in status bar as "Standard PO created under the number 4500290636"
在 SAP 中生成订单,状态栏中的文档编号为“在编号 4500290636 下创建的标准采购订单”
My challenge is how should I convert take string to an Integer value.
我的挑战是我应该如何将字符串转换为整数值。
回答by Eduardo
Since you are using SAP, I think it is safe to assume that the document number will always have a length of 10 characters. So, you can extract it using the Right
function, then just convert it using Val
. Something like this:
由于您使用的是 SAP,我认为可以安全地假设文档编号的长度始终为 10 个字符。因此,您可以使用该Right
函数提取它,然后使用Val
. 像这样的东西:
yourInteger = Val(Right(yourSAPString, 10))
Note: in .net, you could use Convert.ToInt32 instead of Val
注意:在 .net 中,您可以使用 Convert.ToInt32 而不是 Val
回答by The_Barman
You could use the split function:
您可以使用拆分功能:
Dim strSplit As Variant
Dim yourNumericOut As Variant
strSplit = Split("Standard PO created under the number 4500290636")
If IsNumeric(UBound(strSplit)) Then yourNumericOut = --strSplit(UBound(strSplit))
Then test for numeric, will allow for many lengths and could change the position of the number in the returned values.
然后测试数字,将允许多种长度,并可以更改返回值中数字的位置。
回答by HackSlash
I would recommend using a custom function.
我建议使用自定义函数。
Here is the function:
这是函数:
Public Function ExtractNumber(fromString As String) As Double
Dim RegEx As Object
Set RegEx = CreateObject("VBScript.RegExp")
With RegEx
.Pattern = "(\d{1,3},?)+(\.\d{2})?"
.Global = True
If .Test(fromString) Then
ExtractNumber = CDbl(.Execute(fromString)(0))
End If
End With
End Function
Here is the usage example:
下面是使用示例:
Sub Example()
Debug.Print ExtractNumber("Standard PO created under the number 4500290636")
End Sub
This code was taken from a similar, more recent answer that has better solutions. See here: Excel VBA - Extract numeric value in string
此代码取自具有更好解决方案的类似的最新答案。请参阅此处: Excel VBA - 提取字符串中的数值