Help with VBA code to assign numbers based on cell values?

Coyotex3

Active Member
Joined
Dec 12, 2021
Messages
496
Office Version
  1. 365
Platform
  1. Windows
Hello guys, trying to figure out how to go from this:

Book3
AB
1Apple
2Apple
3Apple
4Apple
5Apple
6Orange
7Orange
8Orange
9Orange
10Mango
11Mango
12Mango
13Mango
14Mango
15Mango
16Mango
17Mango
18Mango
19Mango
20Grape
21Grape
22Grape
23Grape
24Grape
25Grape
Sheet1


To this:

Book3
AB
1Apple1
2Apple1
3Apple1
4Apple1
5Apple1
6Orange2
7Orange2
8Orange2
9Orange2
10Mango3
11Mango3
12Mango3
13Mango3
14Mango3
15Mango3
16Mango3
17Mango3
18Mango3
19Mango3
20Grape4
21Grape4
22Grape4
23Grape4
24Grape4
25Grape4
26
Sheet1


I essentially want Excel to assign a number value to each different item starting with 1.

Note: The amount of items changes each time.
 

Excel Facts

Get help while writing formula
Click the italics "fx" icon to the left of the formula bar to open the Functions Arguments dialog. Help is displayed for each argument.
VBA Code:
Sub myFunction()
  Dim lRow As Integer
  lRow = Cells(Rows.Count, 1).End(xlUp).Row
  Cells(1, 2).Value = 1
  For i = 2 To lRow
    If  Cells(i, 1).Value = Cells(i-1, 1).Value Then
      Cells(i,2).Value = Cells(i-1,2).Value
    Else
      Cells(i, 2).Value = Cells(i-1, 2).Value + 1
    End If
  Next
End Sub
 
Upvote 0
Solution
If B1 contained 1, a formula would work too if that will help. Something like
=IF(A2=A1,B1,B1+1)
dragged down from B2
 
Upvote 0
Another way:
VBA Code:
Sub Coyotex3()
Range("B1").Value = 1
With Range("B2:B" & Cells(Rows.Count, "A").End(xlUp).Row)
.Formula = "=IF(A2=A1,B1,B1+1)"
.Value = .Value
End With
End Sub
 
Upvote 0

Forum statistics

Threads
1,215,267
Messages
6,123,964
Members
449,137
Latest member
yeti1016

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top