For循环中的代码未执行

时间:2017-05-15 11:11:53

标签: vba excel-vba excel

我有以下宏:

Sub CalculateCQ()
    'Part I: copy sample names
    Dim SourceExcel As String, CQVals(1 To 8) As Single, RowNum As Integer, i As Integer, j As Integer
    SourceExcel = Application.GetOpenFilename()

    Workbooks.Open (SourceExcel)
    Worksheets("Samples").Activate

    Range("B2:B13").Copy
    Windows("testbook.xlsx").Activate
    Range("A3").PasteSpecial xlPasteValues

    'Part II: copy CQ IR values
    For i = 1 To i = 12 Step 1
        Windows(SourceExcel).Activate
        Worksheets("CQ").Activate

        MsgBox "Running thought sample"
        For j = 1 To j = 8 Step 1
            RowNum = 2 + 25 * (i - 1) + 3 * (j - 1)

            If Cells(RowNum, 5).Value = "inf" Or Cells(RowNum, 5).Value = "N/A" Then
                CQVals(j) = 10000.1
            Else
                CQVals(j) = Val(Cells(RowNum, 5).Value)
            End If
            MsgBox CQVals(j)
        Next j

        Windows("testbook.xlsx").Activate
        'Cells((i + 2), 2).Value = Application.WorksheetFunction.Average(CQVals)
        Cells((i + 2), 2).Value = "Test"
    Next i
End Sub

第一部分是已经过期的,但第二部分似乎根本没有被执行。当尝试使用MsgBox缩小问题时,我发现第一个for循环内部没有任何内容(For i = 1 To i = 12 Step 1)没有被执行。

  • "testbook.xlsx"是宏工作簿

1 个答案:

答案 0 :(得分:1)

for循环的正确语法是

For i = 1 To 12 Step 1
For j = 1 To 8 Step 1

请注意Step 1是默认值,因此没有必要。