You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA中如何基于x分隔符从混合字符串提取长宽数值计算打印面积

解决方案

核心思路

  • 优先匹配大小写不敏感的x两侧紧邻的整数/浮点数作为长宽,完全过滤x之前的无关数字
  • 提取长宽后再从剩余内容中匹配末尾数字作为件数

正则规则说明

匹配长宽的正则表达式为:(\d+\.?\d*)\s*[xX]\s*(\d+\.?\d*)

  • 捕获组1:x左侧的整数/浮点数,对应长度
  • \s*:兼容x左右存在的任意空格
  • [xX]:适配大小写两种x的写法
  • 捕获组2:x右侧的整数/浮点数,对应宽度

VBA实现代码

Function ExtractPrintParams(ByVal inputStr As String) As Variant
    Dim regex As Object
    Dim match As Object
    Dim length As Double, width As Double, qty As Integer
    Dim remainingStr As String
    
    ' 正则晚绑定,无需提前引用库
    Set regex = CreateObject("VBScript.RegExp")
    regex.Global = True
    regex.IgnoreCase = True
    
    ' 第一步:提取长宽
    regex.Pattern = "(\d+\.?\d*)\s*[xX]\s*(\d+\.?\d*)"
    If regex.Test(inputStr) Then
        Set match = regex.Execute(inputStr)(0)
        length = CDbl(match.SubMatches(0))
        width = CDbl(match.SubMatches(1))
        ' 移除匹配到的长宽部分,后续提取件数
        remainingStr = regex.Replace(inputStr, "")
    Else
        ' 无x匹配的场景可自定义默认返回值
        ExtractPrintParams = Array(0, 0, 0)
        Exit Function
    End If
    
    ' 第二步:提取件数,匹配剩余内容末尾的数字
    regex.Pattern = "[- ]+(\d+)\D*$"
    If regex.Test(remainingStr) Then
        Set match = regex.Execute(remainingStr)(0)
        qty = CInt(match.SubMatches(0))
    Else
        qty = 1 ' 未匹配到件数默认1件
    End If
    
    ExtractPrintParams = Array(length, width, qty)
End Function

样例测试结果

调用上述函数对给出的样例测试,返回结果如下:

  • 输入"Canvas 36.5 X 48 piece-10":返回[36.5, 48, 10]
  • 输入"wallpaper 3""X27""":返回[3, 27, 1]
  • 输入"Banner 49x87 -10":返回[49, 87, 10]
  • 输入"14 Vinyl 38 x 9.7":返回[38, 9.7, 1]
  • 输入"wallpaper 3ftX2Ft PC-1":返回[3, 2, 1]

内容的提问来源于stack exchange,提问作者Chetan Nahar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 05:48:01