Copying and pasting loop in VBA Excel for multiple outputs

一个人想着一个人 提交于 2020-07-09 07:13:12

问题


So I have the following excel tabs: Code 1, Code 2, Code 3, LI, 2015, 2016, 2017, 2018, 2019, output for 2015 etc.

For 2015, I have a table in '2015' tab with 10 rows a list of 3 code and their respective % values. e.g.

ref       name   yr     code 1   %     code 2   %      code 3    %
12345   NAME    2015    AB  50% CD  37% EF  13%
78901   NAME    2015    AX  54% OD  30% NG  6%
26572   NAME    2015    AE  60% CD  27% PF  13%

I need the code 1 'AB' and % '50%' to be put into cells B5 and B6 in the tab Code 1. Same for codes 2 and 3 'CS' and '37%' in B5 and B6 in tab Code 2 etc. These then produce an pattern in the LI tab in cells F5:F183 which then needs copying for each reference and pasting into the output for 2015 tab for each reference. Then this loops for each reference and repeats pasting the output.

So far I have this for the copying and pasting part:

    Sub Copy_and_paste2()
        Dim rng2 As Range, cell2 As Range
        Dim i As Integer
        i = 3
        Set rng2 = Worksheets("2015").Range("D10:D21")
        For Each cell2 In rng2
           Worksheets("Code 1").Range("B5").Value = cell2.Value  
            Worksheets("2015 output").Range("A" & i & ":AW" & i).Value = Worksheets("LI").Range("F5:F183").Value
            i = i + 1
        Next cell2
End Sub

At this point I was just trying to make it work for the first code with no % then I can try add the later ones but this one doesn't work either. Any advice?


回答1:


Your question is a little hard to read so I've written an answer based on what I think is the most obvious issue with your code. Apologies if I've misread your query or missed the point entirely..

You appear to be trying to copy the contents of

Worksheets("LI").Range("F5:F183") (179 cells)

to

Worksheets("2015 output").Range("A" & i & ":AW" & i) (49 cells)

Ignoring the fact that you can't copy 179 entries into 49 (it will only copy the first 49) - I think you are probably seeing the first entry repeated across all 49 cells?

This would be because you're not transposing the range (in this case, switching from a column to a row).

Try something like this to Transpose:

Worksheets("2015 output").Range("A" & i & ":AW" & i).Value = _
                WorksheetFunction.Transpose(Worksheets("LI").Range("F5:F57").Value)

Keep in mind though, I've changed the source range to just the first 49 cells. You don't have to but I'm highlighting it in case you weren't aware this is happening.



来源:https://stackoverflow.com/questions/59068514/copying-and-pasting-loop-in-vba-excel-for-multiple-outputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!