Select single column to sort by column number

music_al

Board Regular
Joined
Nov 26, 2008
Messages
133
Hi

Could anyone please tell me why this doesnt work...

I get the error "Compile error: Invalid or unqualified reference"

Sub SortColumns()


Dim CurSortCol As Integer
CurSortCol = 7
Do Until CurSortCol = 295

Sheets("Level3Suppliers").Columns(CurSortCol).Select
ActiveWorkbook.Worksheets("Level3Suppliers").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Level3Suppliers").Sort.SortFields.Add Key:=Range(.Cells(2, CurSortCol), .Cells(3097, CurSortCol)), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Level3Suppliers").Sort
.SetRange Range(.Cells(1, CurSortCol), .Cells(3097, CurSortCol))
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
CurSortCol = CurSortCol + 1
Loop

End Sub
 

Excel Facts

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).
The dot before Cells means "use the reference established by the prior With statement", but there isn't one.
 
Upvote 0
BTW, this should do the same thing:

Code:
Sub SortColumns()
  Dim iCol          As Long

  For iCol = 7 To 295
    With Worksheets("Level3Suppliers").Columns(iCol)
      .Range("A2:A3097").Sort Key1:=.Range("A2"), Order1:=xlAscending, Header:=xlYes
    End With
  Next iCol
End Sub
 
Upvote 0

Forum statistics

Threads
1,217,356
Messages
6,136,079
Members
449,988
Latest member
Mabbas

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