无法在Excel中运行Loop功能

时间:2018-11-26 22:08:18

标签: excel vba loops

我得到了这段代码,但是它似乎并没有一直运行到最后。卡住,调试器仅突出显示Loop关键字或i = i + 1行。我究竟做错了什么?

我尝试了IfFor … Next语句,但似乎没有任何作用。

Sub Macro1()
    '
    ' Macro1 Macro
    '
    Dim i As Integer    
    i = 2

    Do Until i > 586
        Range("B2").Formula = "=sheet2!CS" & i & ""
        Range("B3").Formula = "=sheet2!CR" & i & ""
        Range("B4").Formula = "=sheet2!CQ" & i & ""
        Range("B5").Formula = "=sheet2!CP" & i & ""
        Range("B6").Formula = "=sheet2!CO" & i & ""
        Range("B7").Formula = "=sheet2!CN" & i & ""
        Range("B8").Formula = "=sheet2!CM" & i & ""
        Range("B9").Formula = "=sheet2!CL" & i & ""
        Range("B10").Formula = "=sheet2!CK" & i & ""
        Range("B11").Formula = "=sheet2!CJ" & i & ""
        Range("B12").Formula = "=sheet2!CI" & i & ""
        Range("B13").Formula = "=sheet2!CH" & i & ""
        Range("B14").Formula = "=sheet2!CG" & i & ""

        'Copy and PasteSpecial a Range
        Range("AL18").Copy
        Worksheets("Sheet2").Range("CV" & i & "").PasteSpecial Paste:=xlPasteValues

        i = i + 1
    Loop
End Sub

2 个答案:

答案 0 :(得分:0)

我测试代码时似乎没有任何问题。

这是您的代码,尽管缩短了代码,看它是否有效。

Sub Macro1()
    Dim i As Long, j As Long
    Dim colltr As String

    For i = 2 To 586
        For j = 2 To 14
            colltr = Split(Cells(1, 99 - j).Address, "$")(1)
            Range("B" & j).Formula = "=sheet2!" & colltr & i
        Next j
    'Copy and PasteSpecial a Range

    Worksheets("Sheet2").Range("CV" & i & "").value = Range("AL18").value
    Next i

End Sub

答案 1 :(得分:0)

一个简单的慢版本

Sub LoopTrouble()
  Dim i As Integer
  Dim j As Integer
    For i = 2 To 586
      For j = 1 To 13
        Sheet1.Cells(j + 1, 2) = Sheet2.Cells(i, 98 - j)
'        Sheet1.Cells(j + 1, "B") = Sheet2.Cells(i, 98 - j)
'        Sheet1.Range("B" & j + 1) = Sheet2.Cells(i, 98 - j)
      Next
      Sheet2.Cells(i, 100) = Sheet1.Cells(18, 38)
    Next
End Sub

更快的“半”阵列版本

Sub LoopTroubleFaster()
  Dim i As Integer
  Dim j As Integer
  Dim vntLT As Variant
  Dim vntPaste As Variant
    vntLT = Sheet2.Range(Cells(2, 85), Cells(586, 97)).Value2
    ReDim vntPaste(1 To 13, 1 To 1)
    For i = 1 To 585
      For j = 1 To 13
        vntPaste(j, 1) = vntLT(i, j)
      Next
      Sheet1.Range("B2:B14") = vntPaste
      Sheet2.Cells(i + 1, 100) = Sheet1.Cells(18, 38)
    Next
End Sub