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
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying
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
 
Upvote 0
Solution

Forum statistics

Threads
1,214,994
Messages
6,122,633
Members
449,092
Latest member
bsb1122

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