VBA循环复制列

时间:2015-02-05 03:00:15

标签: vba loops excel-vba excel

我想从一张纸上复制一个定义的数字(比方说10)行(" Data")并将其粘贴到另一张纸上("输入)。这将导致一堆东西计算。然后我想将所计算的数据(6行)从("输入")复制到("数据")并粘贴到结果表中。对于一定数量的列,我会重复这个定义的次数(比方说10)。

我尝试编写代码,但自编写代码以来已经有好几年了。

我使用了Record Marco的东西,得到了这个:

Sub Macro2()
'
' Macro2 Macro
'

'
    Range("C5:C14").Select
    Selection.Copy
    Sheets("Input").Select
    Range("C5").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("P12:P19").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Data").Select
    Range("C22").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("D5:D14").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Input").Select
    Range("C5").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("P12:P19").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Data").Select
    Range("D22").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("G16").Select
End Sub

我希望这是有道理的

1 个答案:

答案 0 :(得分:0)

Sub Macro2()

    Const NUM_TIMES As Long = 10
    Dim shtInput As Worksheet, shtData As Worksheet
    Dim rngCopy As Range, i As Long

    Set shtInput = Sheets("Input")
    Set shtData = Sheets("Data")

    Set rngCopy = shtData.Range("C5:C15")

    For i = 1 To NUM_TIMES

        With shtInput
            .Range("C5").Resize(rngCopy.Rows.Count, 1).Value = rngCopy.Value
            .Calculate
            rngCopy(1).Offset(17, 0).Resize(8, 1).Value = .Range("P12:P19").Value
        End With

        Set rngCopy = rngCopy.Offset(0, 1)
    Next i

End Sub