Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
VBA排序使用相对引用而不是绝对引用创建错误_Vba_Sorting_Runtime Error - Fatal编程技术网

VBA排序使用相对引用而不是绝对引用创建错误

VBA排序使用相对引用而不是绝对引用创建错误,vba,sorting,runtime-error,Vba,Sorting,Runtime Error,我遇到了一个最奇怪的错误,把我难住了。我通过VBA进行排序,我想使用相对引用,这样我就可以一次有效地对电子表格的多个区域进行排序 代码: 这很有效。但是,如果我在代码上方添加: Dim CMVTopCell as Range Set CMVTopCell = Range("I19") 我收到运行时错误“1004”:对象“\u Global”的方法“Range”失败。我应该注意到,最终代码如下所示: Dim CMVTopCell as Range Set CMVTopCell = Range("

我遇到了一个最奇怪的错误,把我难住了。我通过VBA进行排序,我想使用相对引用,这样我就可以一次有效地对电子表格的多个区域进行排序

代码:

这很有效。但是,如果我在代码上方添加:

Dim CMVTopCell as Range
Set CMVTopCell = Range("I19")
我收到运行时错误“1004”:对象“\u Global”的方法“Range”失败。我应该注意到,最终代码如下所示:

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

感谢您的任何帮助

CMVTopCell已经是一个范围,因此不需要将其包装在
range()
中。此外,确保使用工作表对象限定所有范围引用(例如,您不能定义与排序范围不同的工作表上的键,如果
Options
不是活动工作表,则在此操作)。
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
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