Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

vba - Add lines and duplicate data a set number of times

I am trying to write a VBA Excel Macro to look through hundreds of thousands of lines of data to make sure that each unique entry in column A has a number of entries equal to column C.

For example: Messy Data

Source Account Id 84512 occurs 6 times but there needs to be 12 occurrences (as indicated by column C). This means I need to add 6 lines, before (or after) the existing 6 lines.

Next we see Source Account Id 64857 occurs once but needs to occur 5 times. I would add 4 lines above and have the same Source Account Id code and the same Account Name. The rest of the cells can be "0".

Here is an example of the finished product: Clean Data

Here is what I have so far:

Sub InsertRowAtChangeInValue()
   Dim lRow As Long
   Dim nMonths As Long
   
   For lRow = Cells(Cells.Rows.count, "A").End(xlUp).Row To 2 Step -1
    nMonths = 12 - Cells(Application.ActiveCell.Row, 3).Value
      If Cells(lRow, "A") <> Cells(lRow - 1, "A") Then Rows(lRow).EntireRow.Resize(nMonths).Insert
   Next lRow
End Sub
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this after renaming the referenced worksheet.

Sub expandMonths()
    'https://stackoverflow.com/questions/52304181
    Dim i As Long, j As Long, m As Long, a As Variant

    With Worksheets("sheet1")

        i = .Cells(.Rows.Count, "A").End(xlUp).Row
        Do While i > 1
            a = Array(.Cells(i, "A").Value2, .Cells(i, "B").Value2, 0, 0, 0, 0)
            m = .Cells(i, "C").Value2
            j = Application.Match(.Cells(i, "A").Value2, .Columns("A"), 0)

            If i - j < m Then
                .Rows(j).Resize(m - (i - j) - 1, 1).EntireRow.Insert
                .Cells(j, "A").Resize(m - (i - j) - 1, UBound(a) + 1) = a
                .Cells(j, "C").Resize(m - (i - j) - 1, 4).NumberFormat = "0"
            End If

            i = j - 1
        Loop
    End With

End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...