PDA

View Full Version : Solved: Sorting



zoom38
02-26-2006, 11:38 PM
Im in the learning stage using VBA and this is a beginners program that simulates generating random numbers. I have a vba sub that creates rows of numbers. The number of rows of data depends on user input to the question "How many rows of numbers do you need?" Say I enter 10. Now I have 10 rows of numbers. What I want to do is to sort each row of numbers ascending left to right. I've been able to sort each row by a macro for each row but that gets to be ridiculously tedious, say I want 150 rows of numbers. I can't seem to figure out how to do it row by row as it is generated. Any Ideas. Thanks Gary

Jacob Hilderbrand
02-27-2006, 01:03 AM
Try this macro:


Option Explicit

Sub Sort()

Dim i As Long
Dim LastRow As Long

LastRow = Range("A65536").End(xlUp).Row
For i = 1 To LastRow
Range("A" & i).EntireRow.Sort Key1:=Range("A" & i), Order1:=xlAscending, _
Orientation:=xlLeftToRight
Next i

End Sub

zoom38
02-28-2006, 01:29 PM
DR your sort macro doesnt seem to work. It doesnt sort the numbers and I get a "400" error. Since the number of rows of numbers depends on input from the user, I'd like to sort only those rows and limit it to say the first 15 columns. ex:User inputs 5 so there are 5 rows of numbers generated in colum B Thru column P. So I only need a sort for B2:P2 B3:P3 B4:P4 B5:P5 B6:P6 But I would like the macro to be used for any number of rows that would be generated. Thanks Gary

mdmackillop
02-28-2006, 01:55 PM
Option Explicit
Sub RandomNos()
Dim Data As String
Dim Rw As Long, Col As Long, i As Long, j As Long

Data = InputBox("Enter rows, columns", , "15,10")
Rw = Split(Data, ",")(0)
Col = Split(Data, ",")(1)
For i = 1 To Rw
For j = 1 To Col
Cells(i, j) = Int(Rnd * 1000)
Next
Next

For i = 1 To Rw
Range(Cells(i, 1), Cells(i, j)).Sort Key1:=Cells(i, 1), Order1:=xlAscending, _
Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlLeftToRight
', DataOption1:=xlSortNormal 'Last bit for 2003
Next
End Sub

zoom38
02-28-2006, 10:04 PM
Thanks MD your code worked great. There was one problem though, I was receiving an error until I deleted "DataOption1:=xlSortNormal". Thanks Again Gary

mdmackillop
03-01-2006, 01:00 AM
Sorry, That's a 2003 thing which seems to serve no useful purpose. I try to remember to delete it. (Commented out in previous posting)