Select single column to sort by column number

music_al

Board Regular
Joined
Nov 26, 2008
Messages
131
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
 

Some videos you may like

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying

shg

MrExcel MVP
Joined
May 7, 2008
Messages
21,783
Office Version
  1. 2010
Platform
  1. Windows
The dot before Cells means "use the reference established by the prior With statement", but there isn't one.
 

shg

MrExcel MVP
Joined
May 7, 2008
Messages
21,783
Office Version
  1. 2010
Platform
  1. Windows
You're welcome.
 

shg

MrExcel MVP
Joined
May 7, 2008
Messages
21,783
Office Version
  1. 2010
Platform
  1. Windows
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
 

Watch MrExcel Video

Forum statistics

Threads
1,127,668
Messages
5,626,180
Members
416,166
Latest member
Archimed

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
Top