简体   繁体   English

Excel VBA中的双嵌套For循环

[英]Double Nested For Loops in Excel VBA

I am trying to set up a code that first 1.) iterates through a list and replaces values in certain cells and then 2.) copy and pastes values in a list 我正在尝试建立一个代码,该代码首先1.)遍历列表并替换某些单元格中的值,然后2.)复制并粘贴值到列表中

So a made up example: 因此,一个虚构的示例:

 Column A     Column B
   NY          500
   CA          1000
   GA          200

I have a for loop to iterate through column A (to replace values in cells D4,D5,D6 with NY then CA then GA) but I need a second for loop that will copy and paste those values in column B one at a time (eg copy and paste value in B1 into B1 after the first replacement of NY, then B2 into B2 after the replacement of CA, then B3, etc) 我有一个for循环来遍历A列(用NY然后是CA然后是GA来替换单元格D4,D5,D6中的值,然后是NY,然后是CA),但是我需要第二个for循环,一次将这些值复制并粘贴到B列中(例如,在第一次替换NY之后,将B1中的值复制并粘贴到B1中,然后在替换CA之后将B2复制并粘贴到B2中,然后复制B3,依此类推)

Sub Macro2()

    Dim x As Integer
    NumRows = Range("A1", Range("A1").End(xlDown)).Rows.Count
    Range("A1").Select
    For x = 1 To NumRows
        Range("D4") = ActiveCell
        Range("D5") = ActiveCell
        Range("D6") = ActiveCell
        ActiveCell.Offset(1, 0).Select
    Next

End Sub

I think this is what you're asking for... in which case it can all be done in a single loop - no need for a nested loop. 我认为这就是您要的...在这种情况下,可以全部在一个循环中完成-无需嵌套循环。

Sub MM()

    For i = 1 To Cells(1, 1).End(xlDown).Row
        '// Assign the value of Cells(i, 1) [1 = column number] to the range D4:D6.
        [D4:D6] = Cells(i, 1).Value
        '// This is the same as copy -> paste values. Change the "2" for different column
        Cells(i, 2).Value = Cells(i, 2).Value
    Next

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM