vba vba中的应用程序定义或对象定义错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10943930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 16:25:34  来源:igfitidea点击:

Application defined or Object defined Error in vba

excel-vbavbaexcel

提问by Saumil Shah

I am writing following lines of code in the click event of the button which is on Sheet2. But this gives me Object Defined or Application Definederror. If I remove Worksheets("Sheet1")then it will work correctly but it selects Sheet2'srange. I want the range from Sheet1.

我正在按钮的点击事件中编写以下代码行Sheet2。但这给了我Object Defined or Application Defined错误。如果我删除Worksheets("Sheet1")那么它会正常工作,但它选择Sheet2's范围。我想要范围从Sheet1.

So please help me with this.

所以请帮我解决这个问题。

Worksheets("Sheet1").Range(Cells(2, 1), Cells(lastrow, 5)).Sort _
Key1:=Range("E2"), Order1:=xlDescending

回答by Siddharth Rout

That is because your Cellsare not fully defined.

那是因为你Cells没有完全定义。

Try this

尝试这个

With Worksheets("Sheet1")
    .Range(.Cells(2, 1), .Cells(lastrow, 5)).Sort _
    Key1:=.Range("E2"), Order1:=xlDescending
End With

回答by Michal

I had a similar problem with VBA, and I would like to share my solution with you, here is my code:

我在使用 VBA 时遇到了类似的问题,我想与您分享我的解决方案,这是我的代码:

Range("F76").Select
With Selection
.HorizontalAlignment = xlCenter
.Font.Bold = True
.Font.Color = RGB(0, 112, 192)
.Merge
.NumberFormat = "yyyy-mm-dd;@"
With .Validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="=Data"
End With
End With

This fragment caused me trouble. Cell was defined properly (earlier in the code was fragment with sheet activate).

这个片段给我带来了麻烦。单元格定义正确(代码中的早期是带有工作表激活的片段)。

The solution includes only one line of code, I just needed to add

解决方案只包含一行代码,我只需要添加

.Clear

to the code and everything worked again. I hope this will help someone.

到代码,一切又正常了。我希望这会帮助某人。

回答by user3836046

The solution above surely sovles the problem. But simply adding a single row at the top will also work fine.

上面的解决方案肯定会解决问题。但简单地在顶部添加一行也可以正常工作。

Sheets("Sheet1").activate