odd infinite loop

Aquitus 146 Reputation points

i dont actually need an answer for this since i can just hard code after 'To' but i just wanted to share this strange infinite loop that, as far as i can tell, shouldnt be one

    For i = 1 To worksheet.Rows.Count
                If worksheet.Range("A" & i).Value = True Then
                    'do stuff
                ElseIf worksheet.Range("A" & i).Value = nothing Then
                    exit for
                End If
            Next i

in the above code i am iterating through an excel sheet and the A column is always true, false, or blank. but if i run the above code it loops forever
here are some addition things i tried that still result in the same infinite:

If worksheet.Range("A" & i).Value = True Then
                    'do stuff
                ElseIf worksheet.Range("A" & i).Value = false Then
                'i dont put code here so "do nothing" i guess
                    exit for
                End If

select case true/false/else where else is 'exit for'

An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,610 questions
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 27,241 Reputation points Microsoft Vendor

    Hi @Aquitus
    Maybe you can try IsEmpty(worksheet.Range("A" & i)) or worksheet.Range("A" & i).value="" to determine if it is empty.
    Best Regards.
    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Dewayne Basnett 1,361 Reputation points

    If this is Excel Interop...

    Probably not infinite just slow because you are checking all of the rows not the UsedRange.Rows.

    This is a guess...

                    For y As Integer = 1 To XLSheet.UsedRange.Rows.Count
                        Dim r As Excel.Range = CType(XLSheet.Cells(y, 1), Excel.Range)
                        If r.Value IsNot Nothing Then
                            Dim val As String = DirectCast(r.Value, String)
                            If val = "True" Then
                                'do stuff
                            End If
                        End If
                        'For x As Integer = 1 To XLSheet.UsedRange.Columns.Count 'check all columns in row
    0 comments No comments