简体   繁体   中英

How to find the nth non-blank row of a column?

OK... Long story short I found a bug in my code where I thought I could simply find the last row in column "A" (which is row 213). However, I actually needed row 219. This gap may be inconsistent, however there are 17 non-blank cells in column "A" (with the 17th non-blank cell being row 213) and the 17th non-blank cell in column "B" is row 219 (that's the row number I need to extract). So I found this formula:

TagCount = sheet(1).Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count

This returns 17...

Now I need to be able to find the 17th (or whatever TagCount is) non-blank cell in column "B" (Actually I just need the row number).

I had to give in and actually use a loop! This will select the nth filled cell in column B where n is the count of tags in column A. This does assume that column B's format is much like column A, so let me know if this needs to be tweaked to work.

Sub GetMatchingTagInB()

    Dim TagCount As Long
    TagCount = Sheets(1).Range("A:A").Cells.SpecialCells(xlCellTypeConstants).count

    Dim rngB As Range
    Set rngB = Sheets(1).Range("B:B").Cells.SpecialCells(xlCellTypeConstants)

    Dim cel As Range
    For Each cel In rngB
        TagCount = TagCount - 1
        If TagCount = 0 Then
            'do stuff here
            cel.Select
        End If
    Next cel

End Sub

A possible other way of doing it (if I've understood correctly) would be to use the following. I'm evaluating an Excel formula that would find the nth cell in Column B where the nth cell is the count of the number of constants in Column A . This is an array formula which could be evaluated in the sheet but evaluating it in VBA as it is a VBA question.

Dim BRng As Range, nthCell As Range
Dim EvalStr As String

With Sheets(1)
    Set BRng = .Range(.Cells(1, 2), .Cells(.Cells(.Rows.Count, 2).End(xlUp).Row, 2))
End With

EvalStr = "=INDEX(" & BRng.Address & ",SMALL(ROW(" & BRng.Address & ")+(100*(" & BRng.Address & "="""")), COUNTA(A:A)))"
Set nthCell = Application.Evaluate(EvalStr)

MsgBox nthCell.Address

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