问题与SortFields函数和范围

我的问题与下面的代码是,因为我已经定义的范围的select ,我不能在另一张工作表上成功运行此代码。 我知道使用.select是不好的做法,现在我知道为什么,这会导致很多问题。 我不知道如何解决这个代码,以便它能正常工作。

 Sub Sorting(sorted As Range, keys As Range) 'Range("A1:A4").Select sorted.Select Sheets("IDBHour1").Sort.SortFields.Clear Sheets("IDBHour1").Sort.SortFields.Add Key:=keys, SortOn:=xlSortOnValues, _ Order:=xlAscending, DataOption:=xlSortTextAsNumbers With Sheets("IDBHour1").Sort .SetRange sorted .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With End Sub 

你不需要select为了sorting。 在通话过程中如何通过范围?

我个人的偏好是将范围作为string传递,然后使它们进入子范围内。 该代码从任何地方运行。 IDBHour1表不需要select或激活。

 Sub Sorting(sortSheet As String, sorted As String, keys As String) Dim ws As Worksheet Dim sortRange As Range Dim sortKeys As Range Set ws = ThisWorkbook.Sheets(sortSheet) Set sortRange = ws.Range(sorted) Set sortKeys = ws.Range(keys) ws.Sort.SortFields.Clear ws.Sort.SortFields.Add Key:=sortKeys, SortOn:=xlSortOnValues, _ Order:=xlAscending, DataOption:=xlSortTextAsNumbers With ws.Sort .SetRange sortRange .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With End Sub Sub testSort() Call Sorting("IDBHour1", "A1:A10", "A1") End Sub