Excel VBA自定义函数:横向连续编号分组合并的实现问题
修正后的VBA自定义函数实现横向连续编号分组
以下是可以实现横向物料编号连续分组的自定义函数,替换你现有的Lookupsequence函数即可:
Function GroupConsecutiveNumbers(rng As Range) As String Dim lastCol As Integer Dim currentNum As Long, startNum As Long Dim result As String Dim cell As Range ' 获取目标行最后一个非空列 lastCol = rng.Cells(1, Columns.Count).End(xlToLeft).Column ' 初始化起始编号为第一个有效数字 For Each cell In rng.Range(rng.Cells(1, 1), rng.Cells(1, lastCol)) If IsNumeric(cell.Value) And cell.Value <> "" Then startNum = cell.Value currentNum = startNum Exit For End If Next cell ' 遍历后续单元格,判断数字连续性 For Each cell In rng.Range(rng.Cells(1, 2), rng.Cells(1, lastCol)) If IsNumeric(cell.Value) And cell.Value <> "" Then If cell.Value = currentNum + 1 Then ' 数字连续,更新当前结束值 currentNum = cell.Value Else ' 数字不连续,添加当前组到结果 If startNum = currentNum Then result = result & startNum & ", " Else result = result & startNum & "-" & currentNum & ", " End If ' 重置起始和当前值 startNum = cell.Value currentNum = startNum End If End If Next cell ' 添加最后一个分组 If startNum = currentNum Then result = result & startNum Else result = result & startNum & "-" & currentNum End If ' 去除末尾多余的逗号空格 If Right(result, 2) = ", " Then result = Left(result, Len(result) - 2) End If GroupConsecutiveNumbers = result End Function
使用说明
- 打开Excel按
Alt+F11进入VBA编辑器,插入新模块后粘贴上述代码 - 返回工作表,在目标单元格输入公式:
=GroupConsecutiveNumbers(1:1)(1:1代表第一行,可替换为需要处理的行,比如2:2对应第二行) - 回车后即可得到分组结果:如第一行的101、102、103会输出
101-103,第二行的201、202、203、501、502会输出201-203, 501-502
代码核心逻辑
- 自动识别目标行的最后非空列,无需手动指定范围
- 跳过空单元格和非数值单元格,避免运行报错
- 严格判断数字连续性(当前数字=上一数字+1),精准分组
- 单独数字直接显示,不会生成冗余格式
- 自动清理结果末尾多余的分隔符,保证格式整洁
内容的提问来源于stack exchange,提问作者excelquestion11
相关产品推荐
相关产品推荐

