【问题标题】:Get Integer value from String using VBA使用 VBA 从字符串中获取整数值
【发布时间】:2012-10-13 05:51:54
【问题描述】:

我正在尝试使用 QTP 和 SAP 自动化脚本。

在 SAP 中生成订单,状态栏中的文档编号为“在编号 4500290636 下创建的标准采购订单

我的挑战是如何将字符串转换为整数值。

【问题讨论】:

  • 你的数字字符串是否总是出现在末尾,是否总是 10 digita?

标签: vba


【解决方案1】:

由于您使用的是 SAP,我认为可以安全地假设文档编号的长度始终为 10 个字符。因此,您可以使用Right 函数提取它,然后使用Val 对其进行转换。像这样的:

yourInteger = Val(Right(yourSAPString, 10))

注意:在 .net 中,您可以使用 Convert.ToInt32 代替 Val

【讨论】:

    【解决方案2】:

    您可以使用拆分功能:

    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))
    

    然后测试数字,将允许多个长度,并且可以更改数字在返回值中的位置。

    【讨论】:

      【解决方案3】:

      我建议使用自定义函数。

      函数如下:

      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
      

      以下是使用示例:

      Sub Example()
          Debug.Print ExtractNumber("Standard PO created under the number 4500290636")
      End Sub
      

      此代码取自一个类似的、更新的答案,该答案具有更好的解决方案。看这里: Excel VBA - Extract numeric value in string

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-15
        • 1970-01-01
        • 2014-07-24
        • 2020-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-09
        相关资源
        最近更新 更多