继续For循环的条件

时间:2016-11-15 17:57:17

标签: vb.net for-loop if-statement

首先在VB.net中编程并遇到一个小问题。我试图找到一种方法让If语句控制是否在执行另一次迭代之前执行for循环。

代码:

    For Each theTable In tableDoc.Tables
        testString = ""
        For row = 1 To theTable.Rows.Count
            isHeaderOrNot = theTable.Cell(row, 1).Range.Text 'Gets value in first column
            If isHeaderOrNot is Not Like "Section" or "Field" then Continue For 'if the words "Section" or "Field" are NOT included in isHeaderOrNot then continue with For loop
            keyText = theTable.Cell(row, 2).Range.Text
            valueText = theTable.Cell(row, 3).Range.Text
            Console.WriteLine("KEY: {0}", keyText)
            Console.WriteLine("VALUE: {0}", valueText)
            Console.WriteLine("")
        Next
    Next

我在Like上收到错误,说有预期的表达式。

基本上,如果for循环所在的行中的第一列包含Section或Field,我希望它转到下一行。第一次试图解释一个问题,所以任何问题只是问!我非常感谢你的时间!

2 个答案:

答案 0 :(得分:1)

您可以在if中包含整个块,如果不是这种情况,并且您想要结束循环,则可以使用Exit For

For Each theTable In tableDoc.Tables
    testString = ""
    For row = 1 To theTable.Rows.Count
        isHeaderOrNot = theTable.Cell(row, 1).Range.Text

        'If cell doesn't contain Section or Field, then do the following
        If Not isHeaderOrNot.contains("Section") AndAlso Not isHeaderOrNot.contains("Field")
            keyText = theTable.Cell(row, 2).Range.Text
            valueText = theTable.Cell(row, 3).Range.Text
            Console.WriteLine("KEY: {0}", keyText)
            Console.WriteLine("VALUE: {0}", valueText)
            Console.WriteLine("")
        Else

            'If it DOES include Section or Field, then stop looping
            Exit For
        End If
    Next
Next

答案 1 :(得分:1)

正确的语法应该是

If Not isHeaderOrNot Like "Section" AndAlso 
   Not isHeaderOrNot Like "Field" Then 
   Exit For