Extract row indexes of non-empty cells in specific range

Westbury

Board Regular
Joined
Jun 7, 2009
Messages
139
Hi,
I've put this code together to try and put the row indices of the non-blank cells in colB into an array. It fails on ther line "For Each rCell In Range("B2" & Lastrow)" with a Global failure.
What have I done wrong?

VBA Code:
Sub Nonblanks()
Dim Lastrow As Long
Dim rCell As Range
Dim MyArray() As Variant
Dim iLoop As Integer

Lastrow = Cells(Rows.Count, "A").End(xlUp).Row

For Each rCell In Range("B2" & Lastrow)
    ReDim Preserve MyArray(iLoop)
        
        If IsEmpty(Range("B" & iLoop).Value) = False Then
        MyArray(iLoop) = rCell.Row
        End If
    
    iLoop = iLoop + 1
Next rCell
   
   Worksheets("Output").Range("A1").Resize(UBound(MyArray)).Value = Application.Transpose(MyArray)
   
   Erase MyArray
   
End Sub
 

Excel Facts

How to create a cell-sized chart?
Tiny charts, called Sparklines, were added to Excel 2010. Look for Sparklines on the Insert tab.
Try
VBA Code:
For Each rCell In Range("B2:B" & Lastrow)
 
Upvote 0
Thanks Fluff. I've made that edit but now get the same type of failure at

If IsEmpty(Range("B" & iLoop).Value) = False Then

why is this happpening?
 
Upvote 0
perhaps I've found the problem...

If IsEmpty(rCell) = False Then

this appears to work but further down I get an error "overflow runtime 6". This file has almost 290,000 rows. Would puttng the whole worksheet into an array avoid this error?
 
Upvote 0
You will need to make iLoop a Long rather than an integer.
With 290,000 rows pulling col B into an array & looping through that would be a lot quicker.
 
Upvote 0
Solution

Forum statistics

Threads
1,214,385
Messages
6,119,210
Members
448,874
Latest member
b1step2far

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top