Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Excel - Auto next consecutive number

0

I have two sheets. I already have a button to save the data to another sheet called "Data" and it is well working. Now I created one button which needs to do two jobs. It will clear cells (shown in the code) and then it will put in the cell C2 next consecutive number.

Sub ClearButton() Range("L1", "L2").Clear Range("C2", "B3").Clear Range("J5", "K5").Clear End Sub

I want the cell C2 in this Entry sheet to check the column A in another sheet called "Data". In the Data sheet in column A it saves all the customer number as 1,2,3 and carries on. So it must check the last entry or the maximum number in the column A rows. So if the maximum number in Column A(Data Sheet) is 5 then it will put in cell C2(Entry Sheet) 6 so that new entry is done.

Answer
Discuss

Answers

0

Hello Waqar

The code below should do what you want.(click Select All and copy into your workbook).

Note that (in the first bit in bold) I've used a With loop (so the correct sheet is altered no matter which sheet the macro is run from) and that all the clear actions can be combined into the next (single) line of code. I didn't clear C2 (as you did) since the next line overwrites it... 

The bit between the second and third bold bits will locate the last cell in Data and the Entry cell C2 becomes that value plus 1.

Sub ClearButton()

With Worksheets("Entry")
    .Range("L1:L2, B3, J5:K5").Clear
    .Range("C2") = Worksheets("Data").Range("A" & Rows.Count).End(xlUp).Value + 1
End With

End Sub

If you're sure you (or other users) will always run the code from the Entry sheet, you could skip the With loop and use this (the bit line in bold being the essential addition to your original code) :

Sub ClearButton()

Range("L1:L2, B3, J5:K5").Clear
Range("C2") = Worksheets("Data").Range("A" & Rows.Count).End(xlUp).Value + 1

End Sub

Hope this helps.If not, please let me know. If so, please Select the answer.

Discuss


Answer the Question

You must create an account to use the forum. Create an Account or Login