【问题标题】:In excel VBA how do you increase a number in one column by one based on the value changing in another column在excel VBA中,如何根据另一列中的值变化将一列中的数字增加一
【发布时间】:2019-10-02 16:05:44
【问题描述】:

我在 excel 中有两列。一是公司名称。另一列是发票编号,仅应在公司名称更改时增加。应输入起始发票编号 输入起始发票编号 => 1001。每次出现新公司时,增加发票编号的 VBA 代码是什么?

Company A      1001
Company A      1001
Company A      1001
Company B      1002
Company B      1002
Company C      1003

【问题讨论】:

  • 这可以用一个简单的公式来完成。

标签: excel vba


【解决方案1】:

可以通过公式或 VBA 代码解决。

逻辑是看你当前的单元格与公司名称是否和之前的单元格相同。如果它们相同,则复制先前的值。否则将发票编号增加 1。

公式,从单元格C2开始:

=IF(A1=A2,C1,C1+1)

VBA 代码

您可能需要更改列号以使其适合您的数据集。

Sub IncreaseNumber()

Dim ws As Worksheet
Dim lrow As Long
Dim i As Long

Set ws = Worksheets("Sheet1") 'Name the worksheet

lrow = ws.Cells(Rows.Count, "A").End(xlUp).Row 'find the lastrow in column A

For i = 2 To lrow 'Loop from second row to the last row
   If ws.Cells(i - 1, "A").Value = ws.Cells(i, "A").Value Then 'If cell "i -1" and cell "i" is equal then
        ws.Cells(i, "B").Value = ws.Cells(i - 1, "B").Value 'take the same value as row above
    Else
        ws.Cells(i, "B").Value = ws.Cells(i - 1, "B").Value + 1 'if not the same, then add 1 to the invoice number
    End If
Next i

End Sub

【讨论】:

  • 这样做的一个假设是公司列表已排序。在实现上述逻辑之前,我添加了一行以按公司名称对工作表进行排序。
  • 你完全正确@cknowlan。我只是假设 A 列已排序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 2019-06-28
  • 1970-01-01
  • 2020-02-01
相关资源
最近更新 更多