当等于外循环迭代时,如何跳过内循环迭代?

时间:2020-07-21 03:30:51

标签: excel vba

我有一个嵌套的for循环。基本上,我要做的是在第5、6、7、10和11列中有2行或更多行相互匹配时,对14和16列中的值求和。

这可能不是最高效的代码,但是我的代码的要点是,对于k2(参考行)的每次迭代,我希望内部循环将k2与表中除行k2之外的每一行进行比较。 >

现在,问题是在我当前的设置中,当i2-1 = k2的值时,有可能将k2与自己的行进行比较,从而为我的 sumnla 添加一个额外的值和 sumweight

对我来说,克服这个问题的最佳方法是什么?正如您可能会说的那样,我对VBA还是陌生的,到目前为止已有一个月的经验,因此,非常感谢您能更有效地进行编码。

'To consolidate materials, adding nla and weight together
For k2 = ThisWorkbook.Sheets("Summary").UsedRange.Rows.Count To 2 Step -1
    sumnla = ThisWorkbook.Sheets("Summary").Cells(k2, 14).Value
    sumweight = ThisWorkbook.Sheets("Summary").Cells(k2, 16).Value
    valuek = k2

    For i2 = ThisWorkbook.Sheets("Summary").UsedRange.Rows.Count To 2 Step -1
        If _
        ThisWorkbook.Sheets("Summary").Cells(k2, 5).Value = ThisWorkbook.Sheets("Summary").Cells(i2 - 1, 5).Value _
        And ThisWorkbook.Sheets("Summary").Cells(k2, 6).Value = ThisWorkbook.Sheets("Summary").Cells(i2 - 1, 6).Value _
        And ThisWorkbook.Sheets("Summary").Cells(k2, 7).Value = ThisWorkbook.Sheets("Summary").Cells(i2 - 1, 7).Value _
        And ThisWorkbook.Sheets("Summary").Cells(k2, 10).Value = ThisWorkbook.Sheets("Summary").Cells(i2 - 1, 10).Value _
        And ThisWorkbook.Sheets("Summary").Cells(k2, 11).Value = ThisWorkbook.Sheets("Summary").Cells(i2 - 1, 11).Value _
        Then
        sumnla = sumnla + ThisWorkbook.Sheets("Summary").Cells(i2 - 1, 14).Value
        sumweight = sumweight + ThisWorkbook.Sheets("Summary").Cells(i2 - 1, 16).Value
        valuek = valuek & " " & i2
        End If
    Next

    Worksheets("Procurement Table").Select
    
    'add a row at the end of the table
    Dim newrow As ListRow
    Set newrow = ListObj.ListRows.Add
        With newrow
        .Range(1) = Worksheets("Summary").Cells(k2, 10).Value
        .Range(2) = Worksheets("Summary").Cells(k2, 6).Value
        .Range(3) = Worksheets("Summary").Cells(k2, 7).Value
        .Range(4) = Worksheets("Summary").Cells(k2, 11).Value
        .Range(5) = Worksheets("Summary").Cells(k2, 12).Value
        .Range(6) = Worksheets("Summary").Cells(k2, 13).Value
        .Range(7) = 1
        .Range(8) = sumnla
        .Range(9) = "=VALUE([@EngCF])*VALUE([@BaseNLA])"
        .Range(10) = sumweight
        .Range(11) = "=VALUE([@EngCF])*VALUE([@BaseWeight])"
        .Range(12) = 1
        .Range(13) = "=VALUE([@EngFactoredWeight])*VALUE([@FabAllowance])"
        .Range(14) = valuek
        End With
Next

1 个答案:

答案 0 :(得分:-1)

您可以使用goto方法进入下一个循环。您可以编写如下。

if k2 = i2-1 then goto nextLoop

并在nextLoop:末尾写上Next

此外,我的建议是有关引用工作表的更好方法。您可以使用变量来引用工作表。这样,您无需一直写Worksheets("Summary")。您可以通过将新变量定义为工作表来完成此操作。

Dim ws as Worksheet
set ws = Thisworkbook.Worksheets("Summary")