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

如何用VBA提取90位条码指定子串并删除空格?

自定义VBA函数解决条码子串提取与去空格需求

没问题!完全可以通过自定义VBA函数来搞定这个需求,而且用起来灵活又方便。我给你准备了两种实现方式,你可以根据自己的使用习惯选择:

方式一:一次性返回三个处理后的子串(数组形式)

这种方式适合需要同时获取三个结果的场景,返回的数组可以直接在Excel工作表中使用。

打开VBA编辑器(按下Alt+F11),插入一个新模块,粘贴以下代码:

Function ExtractBarcodeParts(originalBarcode As String) As Variant
    ' 先校验条码长度,避免因长度不足报错
    If Len(originalBarcode) < 89 Then
        ExtractBarcodeParts = Array("条码长度不足89位", "条码长度不足89位", "条码长度不足89位")
        Exit Function
    End If
    
    Dim part1 As String, part2 As String, part3 As String
    
    ' 提取第16-35位并删除空格:从第16位开始,取20个字符(35-16+1=20)
    part1 = Replace(Mid(originalBarcode, 16, 20), " ", "")
    ' 提取第35-43位并删除空格:从第35位开始,取9个字符(43-35+1=9)
    part2 = Replace(Mid(originalBarcode, 35, 9), " ", "")
    ' 提取第89位并删除空格:从第89位开始,取1个字符
    part3 = Replace(Mid(originalBarcode, 89, 1), " ", "")
    
    ' 返回包含三个结果的数组
    ExtractBarcodeParts = Array(part1, part2, part3)
End Function

使用方法:

  • 在Excel单元格中输入=ExtractBarcodeParts(A1)(假设原始条码在A1单元格)
  • 新版Excel支持动态数组,直接回车就能在相邻单元格自动填充三个结果;旧版Excel需要按下Ctrl+Shift+Enter作为数组公式输入
  • 也可以用=INDEX(ExtractBarcodeParts(A1),1)单独提取第一部分,INDEX(...,2)提取第二部分,INDEX(...,3)提取第三部分

方式二:独立函数分别提取各部分

如果只需要单独提取某一部分,这种方式更直观:

' 提取第16-35位并去空格
Function ExtractBarcodePart1(originalBarcode As String) As String
    If Len(originalBarcode) < 35 Then
        ExtractBarcodePart1 = "条码长度不足35位"
        Exit Function
    End If
    ExtractBarcodePart1 = Replace(Mid(originalBarcode, 16, 20), " ", "")
End Function

' 提取第35-43位并去空格
Function ExtractBarcodePart2(originalBarcode As String) As String
    If Len(originalBarcode) < 43 Then
        ExtractBarcodePart2 = "条码长度不足43位"
        Exit Function
    End If
    ExtractBarcodePart2 = Replace(Mid(originalBarcode, 35, 9), " ", "")
End Function

' 提取第89位并去空格
Function ExtractBarcodePart3(originalBarcode As String) As String
    If Len(originalBarcode) < 89 Then
        ExtractBarcodePart3 = "条码长度不足89位"
        Exit Function
    End If
    ExtractBarcodePart3 = Replace(Mid(originalBarcode, 89, 1), " ", "")
End Function

使用方法:

  • 直接在单元格中输入=ExtractBarcodePart1(A1)、=ExtractBarcodePart2(A1)或=ExtractBarcodePart3(A1)即可得到对应结果

关键函数说明

  • Mid(字符串, 起始位置, 长度):VBA中提取子串的核心函数,注意字符串索引是从1开始的,所以第16位就是起始位置16
  • Replace(字符串, " ", ""):将子串中的所有空格替换为空字符串,实现删除空格的效果
  • 长度校验:加入长度判断可以避免因条码长度不足导致的错误输出,让函数更健壮

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:20:10