How to repeat all column values for each row in another column

眉间皱痕 提交于 2019-12-13 04:43:09

问题


I have a table that has two columns:

Height Width
400    200
500    300
600    400
700
800
...

And need to create a second table next to it to repeat entire column height for each value in the width column, whilst copying, to basically get every possible combination:

Height Width
400    200
500    200
600    200
700    200
800    200
400    300
500    300
600    300
700    300
800    300

回答1:


The simplest way I could think of running nested loops. You might need to modify the code below depending on the structure of your sheets, but it should get you going.

Sub loops()

Dim n_height, n_width, c As Integer

With ThisWorkbook.Sheets("Sheet1")

n_height = .Cells(Rows.Count, 1).End(xlUp).Row 'Assuming height is in column A
n_width = .Cells(Rows.Count, 2).End(xlUp).Row 'Assuming width is in column B

c = 2

For i = 2 To n_height
    For j = 2 To n_width
        .Range("D" & c).Value = .Range("A" & i).Value 'Prints heights in column D
        .Range("E" & c).Value = .Range("B" & j).Value 'Prints widths in column E
        c = c + 1
    Next j
Next i

End With

End Sub


来源:https://stackoverflow.com/questions/27323364/how-to-repeat-all-column-values-for-each-row-in-another-column

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