VBA:使用另一列中的重复值列表填充列

在Sheet1的B栏中,我有一个与船期相符的部门清单。 我需要将分部从Sheet1(columnB)复制到Sheet2(columnC)。 从第3行到第17行,一旦macros到达第17行的分区,我需要重新开始第3行的分隔,并添加到列的底部。 这是我有,但它不给我任何输出。

For i = 2 To 2 For y = 3 To 17 x = x + 1 Sheets("Sheet2").Cells(x, 3).Value = Sheets("Sheet1").Cells(y, i).Value Next y Next i 

input:

 Atlanta Cincinnati Columbus Michigan Central Louisville Delta Nashville Mid-Atlantic Southwest Charleston Indiana Southwest Dillon California 

输出:

 Atlanta Cincinnati Columbus Michigan Central Louisville Delta Nashville Mid-Atlantic Southwest Charleston Indiana Southwest Dillon California Atlanta Cincinnati Columbus Michigan Central Louisville Delta Nashville Mid-Atlantic Southwest Charleston Indiana Southwest Dillon California 

你的Outer For Loop For i = 2 To 2只运行一次,将它改为For i = 1 To 2运行两次,n运行n次等

 x = 3 For i = 1 To 2 For y = 3 To 17 Sheets("Sheet2").Cells(x, 3).Value = Sheets("Sheet1").Cells(y, 2).Value x = x + 1 Next y Next i 

你可以用一个循环来做到这一点,如果你实例化一些范围variables可能会更容易。 正如其他人所指出的那样,你的外层循环从“2”开始到“2”结束,所以这就是为什么它不是按照你的意图重复的。

 Sub fillValues() Dim i As Integer Dim howManyTimes as Integer Dim copyRange As Range Dim pasteRange As Range Dim rowCount as Long howManyTimes = 2 'modify as needed; tells the procedure how many times to loop '## Define the range to "copy" Set copyRange = Sheets("Sheet1").Range("C3:C17") '## Get the # of rows in this range rowCount = copyRange.Rows.Count '## Define the original destination to "paste": Set pasteRange = Sheets("Sheet2").Range("A3") 'this will be modified later '## Loop and input the values: For i = 1 To howManyTimes pasteRange.Offset((i - 1) * rowCount).Resize(row.Count).Value = copyRange.Value Next End Sub 

尝试:

 set sht1 = ThisWorkbook.sheets("Sheet1") set sht2 = ThisWorkbook.sheets("Sheet2") set rng = sht1.Columns(2).UsedRange j = 1 ' Change for where you want it to start for each cell In rng.cells sht2.cells(1,j) = cell j = j + 1 next cell 

你可以很容易地完成这个没有VBA。 在Sheet2 C列中,input:

=INDEX($B$3:$B$17,MOD(ROW(C1)-ROW($C$1),COUNTA($B$3:$B$17))+1)

只要你想要去复制就可以了。 将$C$1更改$C$1 Sheet2列的第一行。


可选的:

我还build议使用命名范围来让一年之后回来的时候更加容易,而且不记得你在做什么。 那么,做:

Formulas – > Define Name – > Name栏中的DivisionsList=Sheet1!$B$3:$B$17 Refers to: field-> OK

和:

Formulas – > Define Name – > FirstRowName字段中, =Sheet2!$C$1 in Refers to: field-> OK

然后在Sheet2 C列中input下面的内容:

=INDEX(DivisionsList,MOD(ROW(C1)-ROW(FirstRow),COUNTA(DivisionsList))+1)

根据需要更改FirstRow的地址。