简体   繁体   中英

Auto increment column with VBA in Excel

I have an Excel file that is generated by a program that I created to read data from a database and put it in an excel file. I have the 2nd column in my Excel sheet as an identifier column. It should start at B2 with a 1 then in B3 a 2 B4, 3 etc. How do I do this automatically?

The following code will increment +1 based on the row number of Column A from A2 and print the result on B2. If you want it to be triggered in a macro, you can either call the sub from your macro or add the codes to your macro.

Option Explicit

Sub test()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")
    Dim LastRow As Long
    Dim i As Long

    With ws
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = 2 To LastRow
            .Cells(i, 2).Value = i - 1
        Next
    End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM