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

时间:2014-08-06 17:34:56

标签: excel vba excel-vba

在Sheet1的B栏中,我有一个与发货日期一致的分部列表。我需要将分区从Sheet1(columnB)复制到Sheet2(columnC)。分区从第3行到第17行,一旦宏到达第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

输入:

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  

4 个答案:

答案 0 :(得分:1)

你的外循环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

答案 1 :(得分:1)

您可以使用单个循环执行此操作,如果您实例化一些范围变量可能会更容易。正如其他人所指出的那样,你的外循环从“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

答案 2 :(得分:0)

尝试:

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

答案 3 :(得分:0)

如果没有VBA,您可以轻松完成此任务。在Sheet2的C列中,输入:

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

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


OPTIONAL:

我还建议使用命名范围,以便在一年后回来时让生活更轻松,并且不记得你在做什么。所以,做:

Formulas - > Define Name - &DivisionsList位于Name字段,=Sheet1!$B$3:$B$17位于Refers to:字段 - > {{1 }}

OK - > Formulas - &Define Name位于FirstRow字段,Name位于=Sheet2!$C$1字段 - > {{1 }}

然后在Refers to:的C栏中输入此内容并复制下来:

OK

根据需要更改Sheet2的地址。