Yeongjoon Jang
Yeongjoon Jang

Reputation: 17

For loop being skipped without any cause in VBA

Problem: After For currentRow = 25 To rowCount, the rest of the for statement keeps getting skipped for no cause.

I have two other For statements that comes before this problematic block of codes and their formats are the same as this and both work fine.

Public Sub WeightB()
    Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
    Dim currentRowValue As String

    sourceCol = 7
    rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

    For currentRow = 24 To rowCount
        currentRowValue = Cells(currentRow, sourceCol).Value
        If IsEmpty(currentRowValue) Or currentRowValue = "" Then
            Cells(currentRow, sourceCol).Select
            Exit For
        End If
    Next
End Sub

I have referred For loops being skipped without cause in VBA and still haven't been able to figure this out.

Upvotes: 0

Views: 548

Answers (1)

Bathsheba
Bathsheba

Reputation: 234635

If rowCount, as per your clarifying comment, is 22 then your For loop becomes

For currentRow = 24 To 22

which is obviously a no-op, as there is no way 24 can count up to 22. If you need to count in the direction of the final number then you could use something like

For currentRow = 24 To rowCount Step Iif(rowCount - 24 < 0, -1, +1)

but is this really what you want to do? Also, start using Long types for row and column numbers, now that worksheets have more than 32767 rows, and use Option Explicit at the top of all modules to obviate annoying spontaneous variable creation.

Upvotes: 2

Related Questions