在Excel VBA中同时增加两个变量

时间:2018-07-08 19:11:23

标签: excel vba excel-vba

我在Excel VBA中有一些类似这样的代码-

Sub Try()

    Range(Cells(2, 1), Cells(15, 1)).Select
    Selection.Copy
    Sheets("Sheet1").Select
    Range("B2").Select
    ActiveSheet.Paste

    Sheets("Yasheet").Select



    Range(Cells(2, 2), Cells(15, 2)).Select
    Selection.Copy
    Sheets("Sheet1").Select
    Range("B16").Select
    ActiveSheet.Paste

    Sheets("Yasheet").Select


    Range(Cells(2, 3), Cells(15, 3)).Select
    Selection.Copy
    Sheets("Sheet1").Select
    Range("B30").Select
    ActiveSheet.Paste

    Sheets("Yasheet").Select


    Range(Cells(2, 4), Cells(15, 4)).Select
    Selection.Copy
    Sheets("Sheet1").Select
    Range("B44").Select
    ActiveSheet.Paste

    Sheets("Yasheet").Select


    Range(Cells(2, 5), Cells(15, 5)).Select
    Selection.Copy
    Sheets("Sheet1").Select
    Range("B58").Select
    ActiveSheet.Paste





    ActiveWorkbook.Save
End Sub

现在,我显然想在此处增加两个变量,以将代码优雅地放入循环中。

Range(Cells(2, Counter1), Cells(15, Counter1)).Select ' From 1 to 5
    Selection.Copy
    Sheets("Sheet1").Select
    Range("B" & Counter2).Select   ' From 2 , incremented by +14 in each iter
    ActiveSheet.Paste

    Sheets("Yasheet").Select

现在如何在Excel VBA中同时增加两个变量(在此示例中为计数器1和计数器2)。

我记得看到过类似Java或Java的东西,VBA for Excel是否有类似的东西?

谢谢。

2 个答案:

答案 0 :(得分:3)

类似这样的东西:

N/task.SearchTask

答案 1 :(得分:3)

一些数学应该可以进行调整。

sub mytry()
    dim i as long

    with workSheets("Yasheet")
        for i=1 to 5
            .Range(.Cells(2, i), .Cells(15, i)).copy _
              destination:=workSheets("Sheet1").cells(2 +(i-1)*14, "B")
        next i
    end with

end sub