Bob Bob - 20 days ago 5
Vb.net Question

Condition to Continue a For Loop

First go around with programming in VB.net and came across a little issue. I'm trying to find a way to have an

If
statement control whether a
for
loop executes or not before going through another iteration.

Code:

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


I'm getting an error on
Like
saying there's an expression expected..

Basically if the first column in the row the for loop is in contains Section or Field I want it go to the next line. First time trying to explain a question dealing with this, so any questions just ask! I truly appreciate your time!

Answer

You can just include the whole block in the if, and if it's not the case and you want to end the loop, you can use 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 DOESN'T include Section or Field, then stop looping
            Exit For
        End If
    Next
Next
Comments