简体   繁体   中英

Going through columns and setting a range with “Do while” loop in Vba

I have a time series range of data with dates on column A and prices in column B.

This data has "N/A" (a string, not an error) in the first 200 rows (this number is not exact and changes each time I run the file, so I cannot reference it directly).

To be able to graph from a range that does not have the "N/A", I am using a "Do While" loop to go through rows until it is not equal to "N/A", and then setting the range.

Problem: For some reason, my "i" counter is not summing. The loop starts then ends with i = 1, where it should be i = row number from the last "N/A".

The relevant part of the code is:

i = 1
If SourceWorksheet = "Ret" Or SourceWorksheet = "Vol" Then

    Do While w.Sheets(SourceWorksheet).Cells(i, 2) = "N/A"

        i = i + 1     '****Problem IS HERE, IT IS NOT SUMMING TO i

    Loop

    Set RetRange = w.Sheets(SourceWorksheet).Range(Cells(i + 1, 1), Cells(xlLastCell))

Else

    Set RetRange = w.Sheets(SourceWorksheet).UsedRange

End If

Obs 1: In this case I set i = 1, but I already tried not assigning a value for it prior but got an error.

Obs 2: Since this is a function that receive arguments from a sub, the SourceWorksheet is an argument that will be input by the user.

Any ideas on what is wrong with this code?

Apart from a lot of other issues that we had already solved, your loop will fail if cell B1 does not contain "N/A" (eg due to headings).

Try this revised code:

With w.Sheets(SourceWorksheet)
    If SourceWorksheet = "Ret" Or SourceWorksheet = "Vol" Then
        i = 2 ' or i=3, whatever row contains your first item of data
        Do While .Cells(i, 2).Value = "N/A"
            i = i + 1
        Loop

        Set RetRange = .Range(.Cells(i, 1), .Cells.SpecialCells(xlCellTypeLastCell))

    Else

        Set RetRange = .UsedRange

    End If
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM