View Single Post
  #4  
Old 05-21-2006, 11:07 AM
Mike Rosenblum's Avatar
Mike Rosenblum Mike Rosenblum is offline
Microsoft Excel MVP

Forum Leader
* Guru *
 
Join Date: Jul 2003
Location: New York, NY, USA
Posts: 7,802
Default

Yes, iterating through cells one-by-one is very slow, even when using VB 6.0. When using .NET it is even slower because each cell creates a new range object, which is then wrapped within a runtime callable wrapper ("RCW") for each instance. Your code above is creating 65x45 = 2925 COM objects and wrapping them each in a RCW, so this is also 2925 managed .NET objects, each pointing to their COM equivalent...

Ok, so what to do? The solution is to pop all your data into an Array and then iterate that. Unfortunately, you are using the Range.Text property and there is no way to simply return an Array of Text values from a Range of cells into an Array in one shot. If you were willing to go with the Range.Value, however, then you could use use something like this:
Code:
Private Sub ReadCells(ByVal Sht As Excel.Worksheet) Dim rng As Excel.Range With Sht rng = .Range(.Cells(1, 1), .Cells(intRows, intCols)) End With Dim objArray As Object(,) objArray = CType(rng.Value, Object(,)) ' <-- This is the key! Dim intRows As Integer = 45 Dim intCols As Integer = 65 For r As Integer = 1 To intRows For c As Integer = 1 To intCols Dim cellText As String = CType(objArray(r, c), String) If cellText = "1528" Then MessageBox.Show (cellText) End If Next c Next r End Sub
For a discussion of pushing and retrieving an Array of values from an Excel range, you can see the following thread on our sister-forum Extreme Dot Net Talk:

Why is this running so slow?

I hope this helps!
,
Mike
__________________
My Articles:
| Excel from .NET | Excel RibbonX using VBA | Excel from VB6 | CVErr in .NET | MVP |
Avatar by Lebb
Reply With Quote