VBA - 自定义for循环

时间:2016-11-03 11:53:48

标签: excel vba excel-vba for-loop

我想将某些表从一张表复制到另一张表。为此,我有以下代码:

Dim start As Long
Dim eind As Long
Dim output As Long
Dim tbl As Range
Dim dest As Range

output = 5   

For start = 3 To 224 Step 13
        end = start + 10
        Set tbl = Sheets("Model").Range("C" & start & ":E" & end)
        Set dest = Sheets("Sheet1").Range("B" & output).Resize(tbl.Rows.Count, tbl.Columns.Count)
        dest.Value = tbl.Value
        output = output + 16
Next start

但是,此代码将所有表从“Model”复制到“Sheet1”。我只想要名称为A,B,C,E,G,H,J和L的表(名称在D2,D15,D28,D41等)。

有没有办法在for循环之前定义这些特定的表并将其合并到循环中?还是有另一种方法可以做到这一点吗?

非常感谢!

1 个答案:

答案 0 :(得分:0)

我没有在你的代码中进行计算......

(我认为有一个错位:你想从For start = 3 To 224 Step 13循环,但你要检查D2,D15,D28中的名字。所以也许它应该是For start = 2 ....我不确定因为你没有共享你的图表数据结构。)

无论如何,要在循环中添加条件,只需使用以下代码:

For start = 3 To 224 Step 13
    end = start + 10

    Select Case Sheets("Model").Range("D" & start - 1) ' I have "start -1" to adjust to rows 2, 15, 28, etc.

        ' copy only Tables with the following names in Column D...
        Case "A", "B", "C", "E", "G", "H", "J", "L"
            Set tbl = Sheets("Model").Range("C" & start & ":E" & end)
            Set dest = Sheets("Sheet1").Range("B" & output).Resize(tbl.Rows.Count, tbl.Columns.Count)
            dest.Value = tbl.Value

    End Select

    output = output + 16
Next start