How to declare dynamic variable

mmertt900

New Member
Joined
Dec 18, 2020
Messages
11
Office Version
  1. 365
Platform
  1. Windows
Hello All,

I recently begin to learn VBA and I've stuck somewhere in the code and I couldn't figure out how to solve it. I hope you can help me. I'll try to explain as easy as possible. I hope I can explain correctly.Sorry english is not my first language.
What I want to do is there is a spare parts name in excel like below. When spare parts name changed I want to insert a row. Below code works fine but because of cells inserted,code stop working somewhere in the middle and not going all to the end. although I try to make it dynamic with cellnum=cellnum+1,counter variable only consider its first value begging of the code.
Thanks in advance for everybody.
A
A1 abc
A2 abc
A3 bca
A4 bca

VBA Code:
Sub Test()

Dim counter As Integer
Dim cellnum

cellnum = Cells(Rows.Count, 1).End(xlUp).Row

For counter = 1 To cellnum

    If Range("A" & counter) <> Range("A" & counter + 1) Then
    Rows(counter + 1).Insert Shift:=xlDown
    counter = counter + 1
    cellnum = cellnum + 1
    End If
Next counter

End Sub
 

Some videos you may like

Excel Facts

Copy formula down without changing references
If you have =SUM(F2:F49) in F50; type Alt+' in F51 to copy =SUM(F2:F49) to F51, leaving the formula in edit mode. Change SUM to COUNT.

footoo

Well-known Member
Joined
Sep 21, 2016
Messages
3,206
Office Version
  1. 2016
Platform
  1. Windows
VBA Code:
Sub Test()

Dim counter As Integer
Dim cellnum

cellnum = Cells(Rows.Count, 1).End(xlUp).Row

For counter = cellnum To 2 Step -1

    If Range("A" & counter).Value <> Range("A" & counter - 1) Then
    Rows(counter).Insert Shift:=xlDown
    End If
Next counter

End Sub
 
Solution

Watch MrExcel Video

Forum statistics

Threads
1,127,334
Messages
5,624,089
Members
416,010
Latest member
NJT

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
Top