Home » excel » VBA – Trying to add incrementing numbers to an excel cell

VBA – Trying to add incrementing numbers to an excel cell

Posted by: admin May 14, 2020 Leave a comment

Questions:

Sorry, new to VBA and I cant find the answer I need (several close ones though)

I have Col B in a worksheet and its got content to from B1 downwards (B4 in this example).
The number of the last filled cell will be different each time – B4 now in this example, B5 tomorrow, B20 next week.

I want to fill Col A with a number for each cell where B has a value – basically an ID number
The number doesn’t start at 1 & will be different each time.
The number in A1 comes from a cell in another sheet – I just copy it to A1 and I want then to use that as the starting point.
The number will then increment as it progresses down.
Example:

ColA ColB

508 — blab blab

509 — yada yada

510 — etc etc

511 — whatever

in my code,
this fills the cols but just with the value from A1

Dim lastRow As Long                     
lastRow = Range("B" & Rows.Count).End(xlUp).Row
Range("A1").AutoFill Destination:=Range("A1:A" & lastRow)

I tried to add the Row number to the value of A1 and then take away one
(so for row 2 = 2+508-1 = 509)

Range("A2:A" & lastRow).Formula = "=ROW()+A1-1"

BUT when run, the A1 becomes A2 and in the next row its A3 etc so the numbers are out of wack

I tried a few other things and always its not working right; close but no cigar.
I’ve been searching for examples and everything I find is close but not enough.

Q: is there are way to keep the A1 as A1 while this populates the range
OR is there another way of doing this?

Many Thanks

How to&Answers:

Manually place the value in A1 as before, then in A2 enter:

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

and copy down (no VBA needed)

EDIT#1:

If VBA is a requirement then:

Sub dural()
    Dim lastRow As Long
    lastRow = Range("B" & Rows.Count).End(xlUp).Row
    Range("A1").AutoFill Destination:=Range("A1:A" & lastRow), Type:=xlFillSeries
End Sub