简体   繁体   中英

Excel macro, to copy and paste a cell value based on another cell value?

Hi I shall try to explain clearly what I need to be able to do, here goes:

I have an Excel spread sheet 1 with postcodes in column A and a number in column B . I need to create a macro/formula so that it will see the number (ie 3) and copy and paste the postcode that number of times into sheet 2 column a underneath each other. I need to do this for the next row down etc until it comes to a blank.

Sheet 1

A       B
DE43PP  3
DE43PQ  8

Sheet 2

A       B
DE43PP
DE43PP
DE43PP
DE43PQ
...

Thanks

Try this:

Sub copyPostcodes()
    Dim c As Range
    Dim x As Long
    Dim y As Long

    y = 0

    For Each c In Sheets("Sheet1").Range("A:A").Cells
        If Len(c) > 0 Then
            For x = 1 To c.Offset(0, 1)
                Sheets("Sheet2").Range("A1").Offset(y, 0) = c
                y = y + 1
            Next x
        End If
    Next c
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