Condition to Continue a For Loop - vb.net

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!

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 DOES include Section or Field, then stop looping
Exit For
End If
Next
Next

The correct syntax should be
If Not isHeaderOrNot Like "Section" AndAlso
Not isHeaderOrNot Like "Field" Then
Exit For

Related

VBA If Statement within For (Else Running even when If condition is met)

I'm pretty new to VBA and having issues with a Else statements running even when If conditions are met.
Pretty sure this is due to the If statement being within a For & Next
For iCnt = 1 To Len(Firstname)
If IsNumeric(Mid(Firstname, iCnt, 1)) Then
MsgBox "The Firstname cannot contain Numeric values"
ElseIf Len(Firstname) > 100 Then
MsgBox "The Firstname exceeds the character limit (100)"
Else
Sheet3.Cells(lRow, 2).Value = Me.Firstname.Value
End If
Next iCnt
Please any suggestions how to fix this?
Really you only want the first condition to exist in that FOR loop. The rest of it should be tested afterwards and only if that first condition never trips.
Consider instead:
Dim nameHasNumbers as boolean: nameHasNumbers = False
For iCnt = 1 To Len(Firstname)
If IsNumeric(Mid(Firstname, iCnt, 1)) Then
'number found toggle flag and exit the loop
nameHasNumbers = True
exit For
End If
Next iCnt
'Now alert the user or update the name cell
If nameHasNumbers Then
MsgBox "The Firstname cannot contain Numeric values"
ElseIf Len(Firstname) > 100 Then
MsgBox "The Firstname exceeds the character limit (100)"
Else
Sheet3.Cells(lRow, 2).Value = Me.Firstname.Value
End If
For each letter in the name you are going to get the Else to happen. Need to restructure the whole thing. I would put the checking into a function and then based on that result do your other work. If you need a message to inform the user of the reason for the name being invalid add that to the function. Your function can then do other testing on other conditions without affecting your calling code.
Private Function IsValidName(ByVal value As String) As Boolean
If Len(value) > 100 Then
IsValidName = False
Exit Function
Else
Dim charCounter As Long
For charCounter = 1 To Len(value)
If IsNumeric(Mid(value, charconter, 1)) Then
IsValidName = False
Exit Function
End If
Next
IsValidName = True
End If
End Function
When you want to check whether a string includes a digit, you can compare it to a Like pattern which matches a digit: FirstName Like "*[0-9]*"
That approach is simpler than looping through the string checking whether each character is a digit. And since it does not require the For loop, it should be easier to avoid the logic error in your code sample. (As long as the string length did not exceed 100 characters, it wrote a value to Sheet3.Cells(lRow, 2).Value again for each and every non-numeric character contained in FirstName.)
If FirstName Like "*[0-9]*" Then
MsgBox "The Firstname cannot contain Numeric values"
ElseIf Len(FirstName) > 100 Then
MsgBox "The Firstname exceeds the character limit (100)"
Else
Sheet3.Cells(lRow, 2).Value = Me.FirstName.Value
End If

datagridview value already exist vb

this is my code for checking if a value(from dgvlist) already exist in dgvorders, my problem is the error message only shows for the first selectedrow of the dgvlist and the rest still adds.
For Each row As DataGridViewRow In dgvOrders.Rows
For i = 0 To dgvOrders.Rows.Count - 1
If row.Cells(0).Value = dgvList.SelectedRows(i).Cells(0).Value Then
MsgBox("item already listed!", MsgBoxStyle.Critical)
Else : dgvOrders.Rows.Add(v, w, x, y, z)
End If
Exit Sub
Exit For
Next
Next
Because after If statement you are using End sub so once the first record is compared, It is coming out of entire sub.
I suggest you focus on each item in turn. You only want one For Each ... Next loop (unless you also wanted to traverse the columns).
Next get the value to test into a variable ValueFromdgvList. It should be declared as a number or string to match the value expected. I don't know if I have the right syntax or the right value in the code below. You should put a breakpoint in your code and step it so you can check that you have the expected value before starting your compare.
Finally to add a row you need to set the values to an array. Better would be to define a new DataGridViewRow and add the values to that. Finally add it to the DataGridView. But I'll leave that.
'change this as needed
Dim ValueFromdgvList As String = dgvList.SelectedRows(0).Cells(0).Value
Debug.Print(ValueFromdgvList)
Dim haveMatch As Boolean
For Each row As DataGridViewRow In dgvOrders.Rows
If row.Cells(0).Value = ValueFromdgvList Then
haveMatch = True
Exit For
End If
Next
If haveMatch Then
MsgBox("item already listed!", MsgBoxStyle.Critical)
Else
Dim ValuesArray() As Object = {v, w, x, y, z}
dgvOrders.Rows.Add(ValuesArray)
End If
We're using haveMatch because we don't want to add a new row until we've checked all the rows.

if condition true do next for loop iteration

I have code like:
For Each dr As DataRow In items.Tables(0).Rows()
If dr("PRICE") = 0.0 Or dr("PRICE").ToString = "0.0" Then
'Skip end go in for-each again
Else
'Do something else.
End If
Next
I want to know if condition is true (Price is 0) then it should go to next item in for-each and do IF check again. Something like a NEXT?
As asawyer already pointed out, using the Continue Keyword is what you would want to do. It does exactly what you need - it just jumps to the next iteration of the loop specified. In your program it would look like this:
For Each dr As DataRow In items.Tables(0).Rows()
If dr("PRICE") = 0.0 Or dr("PRICE").ToString = "0.0" Then
Continue For
Else
...Do something else.
End If
Next

How to add items to listbox when a loop is involved?

Dim intX, intY As Integer
intY = Nums.GetUpperBound(0)
For intX = 0 To intY
With Nums(intX)
If .strFtID = strID Then
‘calls various subs/functions to get results to show in listbox
listbox.Items.Add(String.Format(strFmt, "various titles”))
listbox.Items.Add(String.Format(strFmt, variable results))
End If
End With
Next
In this loop the listbox for titles is added for every match but I only want it to be added once. I also want to add “no match” if after the entire loop has searched and comes up with no match. There are multiple matches in this loop so it can’t be placed within it or under “else”.
To be able to know if a match was found I usually add a boolean value outside the loop that I call "found". I then set it to false. If the if statement ever is a match i set found to true inside the if. This way when the loop ends I will know if there was a match or not.
Dim found as Boolean = false
For
If
found = true
End if
Next
For the listbox I would do this:
If Not listbox.Items.Contains(String.Format(strFmt, "various titles”)) Then
listbox.Items.Add(String.Format(strFmt, "various titles”))
End if
Try this code, I think this will suits your requirement.
Dim intX, intY As Integer
intY = Nums.GetUpperBound(0)
For intX = 0 To intY
With Nums(intX)
If .strFtID = strID Then
'This following If statement will restricts the duplicate entries, That is
'multiple matches in your words.
If Not listbox.Items.Contains(String.Format(strFmt, "various titles”)) Then
listbox.Items.Add(String.Format(strFmt, "various titles”))
listbox.Items.Add(String.Format(strFmt, variable results))
End if
End If
End With
Next
Now After the loop, just check the count of the listbox. If its count is greater than zero, then some matches had beed found in the upper loop. so that we can leave with out taking any further actions, Other wise just add the word "No Matches" in that listbox, refer the code below,
if listbox.Items.count > 0
listbox.items.add(" NO MATCHES FOUND ")
end if

Data Grid View Replace Value

Can you help me with this..
For Each r As DataGridViewRow In dglist.Rows
For Each c As DataGridViewCell In r.Cells
If c.Value IsNot Nothing Then
**If c.Value.ToString = Label2.Text.ToString Then
c.Value.ToString.Trim.Replace(c.Value.ToString.Trim, TextBox1.Text)
End If**
'MessageBox.Show(c.Value.ToString)
End If
Next
Next
I need to replace the value of the cell with the value of the label.
But still my code did not work.
You need to assign the value (to cell value property) rather than operate on the value of string you have. When you do an operation like ToString etc an additional instance in memory is created and that's all if you are not assigning it. Do this instead:
For Each r As DataGridViewRow In dglist.Rows
For Each c As DataGridViewCell In r.Cells
If c.Value IsNot Nothing Then
**If c.Value.ToString = Label2.Text Then
c.Value = TextBox1.Text
End If**
'MessageBox.Show(c.Value.ToString)
End If
Next
Next
Reconsider your if clauses since I am not very sure that's what you are looking for. In your question you say you want to assign the value of label, but in the code you pasted it seemed to me that you are after text value of your text box.