在Excel中自动更改计数

我有一个Excel工作表,列A应该自动计算之间A4和〜A50(取决于有多less客户端,但通常是大约41 – 43,最多45),当我添加一个新的行。

例如:A4的值为1,A5的值为2,A6的值为3,等到值为40的A43为止。我想在它们之间的某个位置添加一个新的行,数字也会相应地改变。另外,的客户总数增加了,所以A44手机现在拥有新的41。

我search了Google,发现我必须为此编写一个VBmacros(这是真的,不能用更简单的方法解决吗?Excel是如此强大,但它不能这样做)和它有点作用。 但是,当我试图添加一个新行,它不正确行为,表末尾的数字搞砸了一点,它不能正确计数:

Excel计数问题

它总是在同一个区域,38号不会切换到39.不幸的是,我的VB技术是非常有限的,他们已经是5年前,当我上次使用它。 这是脚本:

Private Sub Worksheet_Change(ByVal Target As Range) Dim cntClients As Integer Dim lastCell As Integer Dim startNum As Integer Dim startRow As Integer cntClients = WorksheetFunction.CountA(Range("A4:A60")) lastCell = cntClients + 3 startNum = 1 startRow = 4 Application.EnableEvents = False Do While startRow <= cntClients Range("A" & startRow).Value = startNum startRow = startRow + 1 startNum = startNum + 1 Loop Range("A" & lastCell) = cntClients Application.EnableEvents = True End Sub 

我希望我清楚地说明了自己的观点,如果这个问题有一个更简单的解决scheme,那么可能不使用macros,请让我知道!

如果您需要更多信息,我会很乐意提供给您!

编辑:此外,当我删除新添加的行,数字不会正确更改,如下所示:

Excel问题2

不知何故,macros不喜欢数字39

您正在使用lastCell = cntClients + 3补偿第4行的开始,但从未使用补偿值。

 Private Sub Worksheet_Change(ByVal Target As Range) Dim cntClients As Integer Dim lastCell As Integer Dim startNum As Integer Dim startRow As Integer cntClients = WorksheetFunction.CountA(Range("A4:A60")) lastCell = cntClients + 3 startNum = 1 startRow = 4 Application.EnableEvents = False Do While startRow <= lastCell 'cntClients <~~ this. not that. Range("A" & startRow).Value = startNum startRow = startRow + 1 startNum = startNum + 1 Loop Application.EnableEvents = True End Sub 

我也删除了有相同问题的不必要的行。

没有VBA:

如果将数据表转换为TABLE (可以使用Insert/Table方法),则可以使用如下公式

 A4: =ROW()-3 

并填写。

当您随后插入或删除行时,公式将传播并且数字将正确调整。