i would like a code for autosort left to rigth

  • Thread starter Thread starter Anthony
  • Start date Start date
A

Anthony

i would like a code for autosort left to rigth
eg 1-3-5-7-3-8-4- "- represents blank cell"
1-3-3-4-5-7-8- leaving blank where they are
 
Dear Anthony

Try the below code and feedback which works on Row 1.


Sub SortWOBlanks()
Dim lngCol As Long
Dim lngCount As Long
Dim lngLastCol As Long
Dim varTemp As Variant
Dim arrTemp As Variant

Application.ScreenUpdating = False
lngLastCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
varTemp = Range("A1", Cells(1, lngLastCol))
Range("A1", Cells(1, lngLastCol)).Sort Key1:=Range("A1")
lngCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
arrTemp = Range("A1", Cells(1, lngCol))
Range("A1", Cells(1, lngLastCol)) = varTemp
For lngCol = 1 To lngLastCol
If Cells(1, lngCol) <> "" Then
lngCount = lngCount + 1
Cells(1, lngCol) = arrTemp(1, lngCount)
End If
Next
Application.ScreenUpdating = True

End Sub

If this post helps click Yes
 
Oops. I missed to mention the sort order.. Modified the code so as to call
from code by passing the row to be sorted... such as SortWOBlanks 1 will sort
the first row.

Sub SortWOBlanks(lngRow As Long)
Dim lngCol As Long
Dim lngCount As Long
Dim lngLastCol As Long
Dim varTemp As Variant
Dim arrTemp As Variant

Application.ScreenUpdating = False
lngLastCol = Cells(lngRow, Columns.Count).End(xlToLeft).Column
varTemp = Range(Cells(lngRow, 1), Cells(lngRow, lngLastCol))
Range(Cells(lngRow, 1), Cells(lngRow, lngLastCol)).Sort _
Key1:=Range("A" & lngRow), Orientation:=xlLeftToRight
lngCol = ActiveSheet.Cells(lngRow, Columns.Count).End(xlToLeft).Column
arrTemp = Range(Cells(lngRow, 1), Cells(lngRow, lngCol))
Range(Cells(lngRow, 1), Cells(lngRow, lngLastCol)) = varTemp
For lngCol = 1 To lngLastCol
If Cells(lngRow, lngCol) <> "" Then
lngCount = lngCount + 1
Cells(lngRow, lngCol) = arrTemp(1, lngCount)
End If
Next
Application.ScreenUpdating = True

End Sub

If this post helps click Yes
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

autosort 6
autosort 1
excel 2007 sorting 1
Autosort multiple columns, Keep records intact. 4
Multiple SUM's in a column 15
Gears 14
My Never ending ARRAY code problems 18
Removing Sequential Numbers 4

Back
Top