【发布时间】:2015-02-25 02:13:41
【问题描述】:
我从这个站点复制了一些我认为可以解决我试图解决的问题的代码。我从Using Sort in VBA for a Range that Changes复制了原始代码 我只是将数据的左上角定义为单元格 A3 中的更改方式。最终代码运行如下:
Sub sortOnlySelectedArea()
Dim actSheet As Worksheet
Dim upper, lower As Integer
Dim tempString As String
Dim selectedArea As Range
Set actSheet = Application.Worksheets("Sheet1")
' here you have to put in your part to make the right
'actSheet.Range("E5:G6").Select
ActiveSheet.Range("a3").CurrentRegion.Select
Set selectedArea = Selection
upper = selectedArea.Row
lower = upper + selectedArea.Rows.Count - 1
tempString = "F" & CStr(upper) & ":F" & CStr(lower)
actSheet.Sort.SortFields.Clear
actSheet.Sort.SortFields.Add Key:=Range(tempString), _
SortOn:=xlSortOnValues, Order:=xlAscending,
DataOption:=xlSortNormal
With actSheet.Sort
.SetRange selectedArea
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
我的问题是代码几乎在最后失败了。我已经逐步完成了代码,它正确地拾取了数据区域。当它到达最后一行(.Apply)时它会失败,然后突出显示。调试消息指示运行时错误 1004:排序引用无效。 我无法很好地遵循代码以查看如何选择排序范围。理想情况下,我希望能够对 C 列进行排序,但如有必要,我会选择 A 列。我要排序的范围是 A3:F105。
【问题讨论】:
-
鉴于您使用的是 Range.CurrentRegion,您在 A3:F105 中是否有任何空白行/列?见msdn.microsoft.com/en-us/library/office/…