0

我遇到了让我难过的最奇怪的错误。我正在通过 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

任何和所有的帮助表示赞赏!

4

1 回答 1

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
于 2013-06-18T06:00:58.457 回答