FOR NEXT或FOR EACH LOOP仅适用于第一个值

时间:2015-07-30 10:46:33

标签: excel vba excel-vba

请帮助为以下代码制作For Next循环; 我正在尝试复制范围和范围内的每个单元格。将其传递到特定(固定位置)单元格然后从特定(固定位置)单元格复制结果并将其粘贴到某些单元格。我想为范围内的每个单元格执行此操作。使用Macro我录制了下面的代码,该代码完美无缺但我想从这个录制的宏中制作一个For NEXT或FOR EACH循环,所以请任何人帮助我。

' PastSpecialCheck6 Macro
'

' For L1
    ActiveSheet.Cells(12, 103).Select
    Selection.Copy
    Range("B9").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("B28:B34").Select
    Selection.Copy
    ActiveSheet.Cells(40, 103).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
' For L02
    ActiveSheet.Cells(13, 103).Select
    Selection.Copy
    Range("B9").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("B28:B34").Select
    Selection.Copy
    ActiveSheet.Cells(40, 104).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
' For L03
    ActiveSheet.Cells(14, 103).Select
    Selection.Copy
    Range("B9").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("B28:B34").Select
    Selection.Copy
    ActiveSheet.Cells(40, 105).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

我尝试使用此代码进行循环但是徒劳无功。它仅适用于范围内的一个单元格。

  Sub pastspecialmy_30July2015_2()
 ' Ln is length
 Dim Ln As Variant
 ' i is numbers
 Dim i As Integer

 ' For L1

 For Each Ln In ActiveSheet.Range("CY12:CY30").Cells
   For i = 125 To 143
    ' Ln.Activate
    Range("B9").Select
    Selection.Value = Ln
    Range("B28:B34").Select
    Selection.Copy

    ActiveSheet.Cells(57, i).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
  Next
 Next

 End Sub

1 个答案:

答案 0 :(得分:1)

这是你在尝试的吗?

Sub Sample()
    Dim i As Long, n As Long
    Dim ws As Worksheet

    Set ws = ActiveSheet

    n = 103

    With ws
        For i = 12 To 30
            .Cells(i, 103).Copy
            .Range("B9").PasteSpecial Paste:=xlPasteValues, _
            Operation:=xlNone, SkipBlanks:=False, Transpose:=False

            .Range("B28:B34").Copy
            .Cells(40, n).PasteSpecial Paste:=xlPasteValues, _
            Operation:=xlNone, SkipBlanks:=False, Transpose:=False

            n = n + 1
        Next i
    End With
End Sub