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
629 views
in Technique[技术] by (71.8m points)

vba - every possible combination of the contents of 2 columns in excel

Suppose I have 2 Columns:

1st column(contains 1000 rows):

U-0001

U-0002 

2nd column(contains 10 rows):

B01

B02

B03

Now, I want to generate two columns like this(with 10*1000 = 10000 rows):

U-0001 B01

U-0001 B02

U-0001 B03

U-0002 B01

U-0002 B02

U-0002 B03
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

this should do it:

Sub combineTwoCol()

    ' i,j,k are counters for first col, second col and the answer col in order.
    k = 1
    For i = 1 To 1000
        For j = 1 To 10
            Cells(k, "C").Value = Cells(i, "A").Value
            Cells(k, "D").Value = Cells(j, "B").Value 
            k = k + 1
        Next j
    Next i
End Sub

edited: you should notice that i assumed you have only those two columns is the file, if not change "A" and "B" to the corrosponding columns you need. and "C" and "D" to where you want the two output columns to be.

also if the 10 and 1000 are just examples and not really the values you can always find them dynamically like this:

'this return to the variable the last row in column A
LastRowColA = Range("A65536").End(xlUp).Row

and replace 1000 with LastRowColA


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

...