• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 50
  • Last Modified:

Sorting Spreadsheet Issue

Hi,

I am sorting a spreadhseet by the value of the column A. The first 2 rows are the header. The following code shows an error in the fourth line (Run-time error '1004': Sort method of Range class failed), but if I change the range of the With in the third line to ("A3:AL10")instead of ("A3:AL100") it works properly. Any solution or advice to extend that range to ("A3:AL100") ?

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A3:A100")) Is Nothing Then
With Range("A3:AL100")
.Sort key1:=.Cells(1, 1)
End With
End If
End Sub
0
lnrivera
Asked:
lnrivera
1 Solution
 
SimonCommented:
I can't replicate your error. The code you posted works fine for me. Can you post the workbook?
0
 
gowflowCommented:
For sure you will get an error with a routine like this in an event like this and here is the reason:

You are performing a sort meaning that cells will invoke a change event in a Change event routine without any control on events. reason why you will endup with cascading events launched as a result of the sort which will ultimately cause an error. It is simply by luck that by changing the range you escaped the error. If you insist on doing the sort in the change event here is how to do it.

This is the code and below is a workbook sample you simply change any value in Col A and see the results.

Private Sub Worksheet_Change(ByVal Target As Range)

'---> Disable Events
With Application
    .EnableEvents = False
    .ScreenUpdating = False
    .DisplayAlerts = False
End With

If Not Intersect(Target, Range("A3:A100")) Is Nothing Then
    With Range("A3:AL100")
        .Sort key1:=.Cells(1, 1), Header:=xlNo, MatchCase:=False
    End With
End If

'---> Enable Events
With Application
    .EnableEvents = True
    .ScreenUpdating = True
    .DisplayAlerts = True
End With

End Sub

Open in new window


gowflow
Sort.xlsm
0
 
Martin LissRetired ProgrammerCommented:
I've requested that this question be closed as follows:

Accepted answer: 500 points for gowflow's comment #a40602609

for the following reason:

This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now