我有一个宏,可以将服务台故障单过滤并分类为不同的颜色编码类别和严重性级别。它曾经在Excel 2010中工作,但是我试图在Excel 2016中运行它,并抛出2个错误。
第一个是
“运行时错误91-对象变量或未设置块变量”
似乎停留在这一行:
ActiveWorkbook.Worksheets(SheetName1).AutoFilter.Sort.SortFields.Clear
第二个错误是
“运行时错误'1004'-排序引用无效。请确保它在您要排序的数据中,并且第一个“排序依据”框不相同或为空白“
该错误指向。在下面的代码中应用。
我根本不熟悉VBA代码,所以我很困惑,我从同事那里继承了代码。引发错误的代码段如下。
Range("A1:S1").Select
Rows("1:1").Select
Selection.AutoFilter
Range("V3").Select
ActiveWorkbook.Worksheets(SheetName1).AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets(SheetName1).AutoFilter.Sort.SortFields.Add Key:= _
Range("V1"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets(SheetName1).AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
添加了量化变量SheetName1的代码
'Insert Active.Worksheetname to A300. This is required to allow the filters to function later on, as the worksheet name varies according to the exported CSV file name
ActiveWindow.SmallScroll Down:=288
Range("A300").Select
ActiveCell.FormulaR1C1 = _
"=MID(CELL(""filename"",R[-299]C),FIND(""]"",CELL(""filename"",R[-299]C),1)+1,255)"
Dim SheetName1
SheetName1 = Trim(Range("A300").Value)
任何帮助使此代码正常工作的人将不胜感激。
我现在对该部分进行了如下编辑:
Range("A1:S1").Select
Rows("1:1").Select
Selection.AutoFilter
Range("V3").Select
With ThisWorkbook.Sheets(SheetName1)
.AutoFilterMode = False
.Range("A1").AutoFilter
.AutoFilter.Sort.SortFields.Clear
.AutoFilter.Sort.SortFields.Add Key:=.Range("V1"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With .AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
错误1004仍被抛出并突出显示为“ .Apply”
我真的不是程序员,也不是真正了解代码的人,所以请原谅您对答案的理解不足。
答案 0 :(得分:0)
这是一个基本的代码示例,使用With
语句适当地限制工作表,删除并且不要使用Select
,并提供注释来阐明。
With ThisWorkbook.Sheets(SheetName1) 'If `SHeetName1` is the actual sheet name it must be in parentheses ""
.AutoFilterMode = False 'Remove filters
.Range("A1").AutoFilter
.AutoFilter.Sort.SortFields.Clear 'Will fail if the previous filter was not removed
.AutoFilter.Sort.SortFields.Add Key:=.Range("V1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With .AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With