VBA错误:“运行时错误1004:应用程序定义或对象定义错误”

我是一个完整的新手在vba和编码一般,现在正在跟随一个关于udemy vba课程。 在其中一个练习(dynamicsorting),我不断收到上述错误。 这是非常令人沮丧的卡住这样,而正确地跟随老师..任何帮助表示赞赏。

Sub Sort() ' ' Sort Macro ' ThisWorkbook.Activate Range("a2").Select 'find last row mylr = ThisWorkbook.Sheets("sheet1").Cells(Rows.Count, 1).End(x1up).Row ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("C2:C5"), _ SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal With ActiveWorkbook.Worksheets("Sheet1").Sort .SetRange Range("A1:C5") .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With End Sub 

我不想让你远离课程计划的stream程,但是看起来像手动sorting操作中logging的代码非常冗长。 在现实中,你需要的是以下。

我build议你进入设置VBE工具►选项►编辑器► 需要variables声明或在每个模块代码表顶部手动放置Option Explicit的练习。 目前, x1up常数被拼写错误。

 Sub mySort() ' Sort Macro 'reference the workbook and worksheet With ThisWorkbook.Sheets("sheet1") 'reference the range to receive the sorting method With .Range(.Cells(2, 1), .Cells(Rows.Count, 1).End(xlUp).Offset(0, 2)) 'sort the cells based on the third column in a descending order .Cells.Sort Key1:=.Columns(3), Order1:=xlDescending, _ Orientation:=xlTopToBottom, Header:=xlYes End With End With End Sub 

永远不要将您的子过程命名为保留字 。 这有效地覆盖了该命令或常量的function,以支持较新的名称。 通过命名你的函数Sub Sort() ,然后试图调用Range.Sort方法,你的子程序可以有效地尝试回忆自己。


¹ 在VBE工具中设置需要variables声明 ►选项►编辑器属性页面将把Option Explicit语句放在每个新创build的代码表的顶部。 这将避免像拼写错误这样的愚蠢的编码错误,也会影响你在variables声明中使用正确的variablestypes。 在没有声明的情况下即时创build的variables都是变体/对象types。 使用Option Explicit被广泛认为是“最佳实践”。

错误行?

 mylr = ThisWorkbook.Sheets("sheet1").Cells(Rows.Count, 1).End(x1up).Row 

顺便说一句,myLr用于什么?