我做错了什么?

发布于 2024-11-29 00:53:15 字数 285 浏览 0 评论 0原文

sheet1.activate
activesheet.range(cells(2,"Q"),cells(40,"K")).select 'here the error occurs 
selection.copy

上面的代码有时有效,有时会抛出一个错误,对象变量未设置,这意味着什么?为什么上面的代码不起作用,如果我重新打开文件,它会再次起作用,有时却不起作用。但我不知道发生这种情况的原因。我在语法中犯了任何错误吗?如果有,请告诉我正确的方法。有没有更有效的方法来选择一组范围?除了上述以外?先感谢您

sheet1.activate
activesheet.range(cells(2,"Q"),cells(40,"K")).select 'here the error occurs 
selection.copy

The above code works for somtimes and for sometimes throws an Error that with object variable not set what does that mean ? why the above code is not working and if i reopen the file it works again and sometimes dont. But i dont know the reason why it happens. Am i making any mistake in the syntax, If so please let me know the right way to do it. And is there any more efficient way to do to select a set of range ? other than the above ? Thank you in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤千羽 2024-12-06 00:53:15

这个错误的原因通常是遗漏了Set关键字,例如,

Dim w as Worksheet
w = Sheet1 ' throws error 91
' Correct syntax: 
' Set w = Sheet1 

如果您告诉我们错误发生在哪一行,那么将会得到更具体的答案。您的代码示例的语法看起来不错,但错误可能是由于代码中的另一行造成的,可能没有在您的问题中显示。

有没有更“有效”的方法来选择范围?就我个人而言,我不喜欢您展示的使用字符串作为 Cells 参数的方法。字符串杂乱,经常会导致错误,从而降低工作效率。为什么不:

Sheet1.Range(Cells(2,18),Cells(40,11)).Select
' or
Sheet1.Cells(2,11).Resize(39,8).Select
' or
Sheet1.Range("K2").Resize(39,8).Select

或者,将 K2:Q40 定义为工作表中的命名范围,将其称为“myRange”,然后执行以下操作:

Sheet1.Range("myRange").Select ' My personal favourite

但是为什么要使用Select?这通常是没有必要的。只是写:

Sheet1.Range("myRange").Copy

但是我可以问,为什么你使用 Copy,这本身就是一个混乱的方法?...

The cause of this error is usually the omission of a Set keyword, e.g.

Dim w as Worksheet
w = Sheet1 ' throws error 91
' Correct syntax: 
' Set w = Sheet1 

If you tell us on what line the error occurs, then a more specific answer will be forthcoming. The syntax of your code sample looks fine, but the error may be due to another line in your code, perhaps not shown in your question.

Is there any more "efficient" way to do to select a range? Personally, I don't like the method you show, with strings as the arguments for Cells. Strings are messy, and often lead to mistakes and therefore a loss of work efficiency. Why not:

Sheet1.Range(Cells(2,18),Cells(40,11)).Select
' or
Sheet1.Cells(2,11).Resize(39,8).Select
' or
Sheet1.Range("K2").Resize(39,8).Select

Or, define K2:Q40 as a named range in your sheet, calling it e.g. "myRange", and do this:

Sheet1.Range("myRange").Select ' My personal favourite

But why are you using Select? This is usually not necessary. Just write:

Sheet1.Range("myRange").Copy

But then I could ask, why are you using Copy, which is a messy method in its own right?...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文