我遇到了令我难过的最奇怪的错误。我正在对VBA进行排序,我想使用相对引用,这样我就可以一次有效地对电子表格的多个区域进行排序。
代码:
ActiveWorkbook.Worksheets(Options).Sort.SortFields.Clear
ActiveWorkbook.Worksheets(Options).Sort.SortFields.Add key:=Range("I19"),
Order:=xlDescending
With ActiveWorkbook.Worksheets(Options).Sort
.SetRange Range("a19:x29")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
哪个效果很好。但是,如果我在代码上面添加以下行:
Dim CMVTopCell as Range
Set CMVTopCell = Range("I19")
我得到运行时错误'1004':对象'_Global'的方法'范围'失败。我应该注意到,最终的代码看起来像这样:
Dim CMVTopCell as Range
Set CMVTopCell = Range("I19")
ActiveWorkbook.Worksheets(Options).Sort.SortFields.Clear
ActiveWorkbook.Worksheets(Options).Sort.SortFields.Add key:=Range(CMVTopCell),
Order:=xlDescending
With ActiveWorkbook.Worksheets(Options).Sort
.SetRange Range("a19:x29")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
感谢任何和所有帮助!
答案 0 :(得分:0)
Dim sht as Worksheet
Dim CMVTopCell as Range
set sht = ActiveWorkbook.Worksheets(Options)
Set CMVTopCell = sht.Range("I19")
sht.Sort.SortFields.Clear
sht.Sort.SortFields.Add key:=Range(CMVTopCell), _
Order:=xlDescending
With sht.Sort
.SetRange sht.Range("a19:x29")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With