Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting In Excel

Status
Not open for further replies.

SandraF

Programmer
Jan 25, 2001
28
US
Here is the problem.

I want to sort rows of information by a column using a macro.
The only problem is that there is no set of rows. One time there sould be 4 rows, another day there could be 45

I have the following code so far:
rows.Worksheets("DB").Range("?????????").Sort _
key1:=Worksheets("DB").Range("????")
Set currentCell = Worksheets("DB").Range("????")
I want to sort by Column L then by Column R


I am thinking that before I sort, I should count how many rows there are in the worksheet. Then I could do something with that information. :)

Any info would be appreciated!!
 
Use Range.currentRegion()

A region is a block of cell bounded by blank rows and columns.

I will have to try it and send you the code but meanwhile you can play with it and maybe make it work for you.

I have used it before in similar situation where my area was contantly changing. It works like a champ:) Ya' Gotta Love It!
 
This could tell you how many rows there are:

t1$ = Cells(1, 1).Value
row = 1
If t1$ <> &quot;&quot; Then
row = 2
Do
t1$ = Cells(row, 1).Value
If t1$ = &quot;&quot; Then
maxrow = row - 1
Exit Do
Else
row = row + 1
End If
Loop
End If
 
You don't have to select the specific rows. Just select the entire columns and do the same sort. All empty rows will automatically be ignored.
Code:
Columns(&quot;A:L&quot;).Select
Selection.Sort Key1:=Range(&quot;A2&quot;), Order1:=xlAscending,_
               Header:=xlGuess, OrderCustom:=1, _
               MatchCase:=False, Orientation:=xlTopToBottom
 
This little sub will tell you how many rows you have with something in them:

Sub GetRows()
Dim C As Range
Worksheets(1).Activate
[F10:F10010].Select
For Each C In Selection.Cells
If C.Value <> &quot;&quot; Then
Counter = Counter + 1
End If
Next C
End Sub

You can change the range to be whatever you need to in your case. I usually just give it something huge, to cover any amount of rows that the user could possibly put in; in this case I accounted for 10000 rows. This is also a nice subroutine because it gives the amount of rows back in the variable &quot;Counter&quot;, which I have as a Global variable. Then I can use that count later in analysis.
 
kruskovac, I find it easier to just use:

Worksheetfunction.CountA(Activesheet.Range(&quot;F:F&quot;))
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top