重复宏的代码

时间:2015-10-01 09:29:31

标签: excel vba excel-vba

我需要重复一个名为" DTest"对于具有390行的源电子表格中的给定范围。 " DTEST"宏创建一个新的Excel文件并转置粘贴范围并将文件名保存在单元格" B2"在给定的路径中。

Sub RepeatDTest()

    Range("1:1,2:2").Select
    Selection.Copy
    DTest
    Range("1:1,3:3").Select
    Selection.Copy
    DTest
    Range("1:1,4:4").Select
    Selection.Copy
    DTest
End Sub

我的范围包括第1行作为标题,以及2到390的行作为新电子表格第2行中的内容。

如何为Range编写代码(" 1:1,2:2"),范围(" 1:1,3:3")......范围(" 1:1,390:390")?

1 个答案:

答案 0 :(得分:1)

Sub RepeatTestD()
    ' For every value of i, from 2 until 390, run the following lines of code
    For i = 2 To 390
        ' No reason to do .Select, we can perform .Copy directly on the range. 
        ' This is more precise and is also a much better coding practice.
        ' Using i as an argument in the range reference is the central piece.
        ' For i = 2, the macro will copy the range "1:1","2:2". 
        ' For i = 10, it will be "1:1", "10:10". Ad "i-finitum".
        Range("1:1", i & ":" & i).Copy
        Call DTest
    ' Go to the next value of i and go back to the start of the loop
    Next i
End Sub