简体   繁体   中英

Inserting new row in excel by VBA

I have an excel spreadsheet. In a column of the spreadsheet I have a list of codes (numbers).These codes (numbers) are sorted from highest to lowest values.(some of these codes has been repeated. For example I have three consecutive line with code 1001200).I want to insert new rows between each codes (in case of having repeated codes i just need one new row (for example i Just need one new row for 1001200 not 3 rows) . I have written the following code but it does not work.

Sub addspace()
   Dim space_1(5000), Space_2(5000)

   For n = 1 To 5000
   Debug.Print space_1(n) = Worksheets("sheet3").Cells(1 + n, 1).Value
   Debug.Print Space_2(n) = Worksheets("sheet3").Cells(2 + n, 1).Value
   Next
   For n = 1 To 5000
   If space_1(n) <> Space_2(n) Then

   Range("space_1(n)").EntireRow.Insert

   End If
   Next
   End Sub

How can I fix it? (From the code you can see that I am so beginner :)))

Cheers

To insert one empty row between each unique value try this:

Option Explicit

Public Sub addspace()
    Dim i As Long

    Application.ScreenUpdating = False
    With Worksheets("sheet3")
        For i = 5000 To 2 Step -1
            While .Range("A" & i - 1) = .Range("A" & i)
                i = i - 1
            Wend
            .Rows(i).Insert Shift:=xlDown
        Next
    End With
    Application.ScreenUpdating = True
End Sub

It starts from the end row and moves up, skipping duplicates

The Range("space_1(n)") is invalid. Arg of range object should be a column name like "A1", you can use Range("A" & n).EntireRow.Insert in your code. But I recommend my code.

Please try,

Sub addspace()
Dim n As Integer

For n = 1 To 5000
    If Worksheets("sheet3").Cells(n, 1).Value <> Worksheets("sheet3").Cells(n + 1, 1).Value Then
        Worksheets("sheet3").Cells(n + 1, 1).EntireRow.Insert
        n = n + 1
    End If
Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM