开发者

Copy Paste from Sheet 1 to Sheet 2

I'm a noob at this so any help is appreciated. Need help with writing a script that will copy column A + B and paste to sheet2 a number of times according to value of C. Please see example below. This would save us a tromendous amount of time. Any help would be greatly appreciated.

Sheet1

A       B       C
1111  开发者_运维百科  aaaa     3
2222    bbbb     4
3333    cccc     2

After Macro

Sheet2

A       B       C
1111    aaaa     3
1111    aaaa     3
1111    aaaa     3
2222    bbbb     4
2222    bbbb     4
2222    bbbb     4
2222    bbbb     4
3333    cccc     2
3333    cccc     2


Sub MakeNewTable()

    Dim rCell As Range
    Dim i As Long
    Dim rNext As Range

    'loop through the cells in column A of the source sheet
    For Each rCell In Sheet1.Range("A1:A3")
        'loop as many times as the value in column C of the source sheet
        For i = 1 To rCell.Offset(0, 2).Value
            'find the next empty cell to write to in the dest sheet
            Set rNext = Sheet2.Cells(Sheet2.Rows.Count, 1).End(xlUp).Offset(1, 0)
            'copy A and B from source to the dest sheet
            rCell.Resize(1, 2).Copy rNext.Resize(1, 2)
        Next i
    Next rCell

End Sub

You'll need to change the sheet references to match your situation. The sheet references used above are Codename references. If you open the Project Explorer in the VBE (Control+R), and expand your projection, you'll see objects like 'Sheet1 (MyTablName)'. The Sheet1 portion is called the Codename and doesn't change when you rename the sheet. If you want to use the tab names, you would use something like

ThisWorkbook.Worksheets("MyTabName").Range("A1:A3")

Good luck.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜