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

求实现:上方单元格内容变化时自动+1的Excel公式或VBA代码

按B列分组生成A列序号的实现方案

一、Excel公式实现

方法1:基础判断公式

在A2单元格输入以下公式,下拉填充至所有行:

=IF(B2=B1,A1,A1+1)

注意:A1单元格需手动输入初始值1,对应第一个分组的序号。

方法2:动态分组序号匹配(适用于Excel 365/2021及以上版本)

若你的Excel支持动态数组函数,在A2单元格输入以下公式可自动填充所有行:

=MATCH(B2,UNIQUE($B$2:$B$100),0)

说明:将$B$2:$B$100替换为实际的B列数据范围,公式会自动识别唯一分组并分配对应序号,无需手动下拉。

二、VBA代码实现

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

Sub GenerateGroupNumber()
    Dim lastRow As Long
    Dim i As Long
    Dim groupNum As Integer
    
    lastRow = Cells(Rows.Count, "B").End(xlUp).Row
    groupNum = 1
    Cells(1, "A").Value = groupNum
    
    For i = 2 To lastRow
        If Cells(i, "B").Value <> Cells(i - 1, "B").Value Then
            groupNum = groupNum + 1
        End If
        Cells(i, "A").Value = groupNum
    Next i
End Sub

运行该宏后,A列会自动根据B列分组生成对应序号。

内容的提问来源于stack exchange,提问作者Máté Kiss

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:15:30