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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1753550/
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 11:00:57  来源:igfitidea点击:

Excel VBA pastelink run-time error 1004: Application-defined or object-defined error

excelvba

提问by z -

I am trying to create a link from a cell on one sheet to a cell on the other sheet, but when I run it I get this runtime error:

我正在尝试创建从一张纸上的单元格到另一张纸上的单元格的链接,但是当我运行它时,出现此运行时错误:

Application-defined or object-defined error.

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

Here is the code:

这是代码:

Worksheets(sheetFrom).Cells(fromRow, fromCol).Copy
Worksheets(sheetTo).Cells(toRow, toCol).Select
ActiveSheet.Paste Link:=True

I am checking the to/from values and they are correct.

我正在检查 to/from 值,它们是正确的。

updateseems like its the cell selection that's causing the problem.

更新似乎是导致问题的单元格选择。

update 2When the from sheet is the same as to sheet, there is no problem. What am I missing?

update 2from sheet和to sheet一样的时候就没有问题了。我错过了什么?

回答by dendarii

You're getting that error because Worksheets(sheetTo) is not the active sheet when you're trying to paste to it.

您收到该错误是因为 Worksheets(sheetTo) 在您尝试粘贴时不是活动工作表。

If you add a line to your code

如果您在代码中添加一行

Worksheets(sheetFrom).Cells(fromRow, fromCol).Copy
Worksheets(sheetTo).Activate
Worksheets(sheetTo).Cells(toRow, toCol).Select
ActiveSheet.Paste Link:=True

it works.

有用。

Edit to respond to guitarthrower's answer:

编辑以回应吉他手的回答:

Paste link, as far as I can tell, only works with Worksheet.Paste, not Range.Paste. Worksheet.Paste pastes the link into the active cell. Although I agree with you that Select should be avoided, using this type of code seems to require it.

据我所知,粘贴链接仅适用于 Worksheet.Paste,不适用于 Range.Paste。Worksheet.Paste 将链接粘贴到活动单元格中。虽然我同意你应该避免 Select,但使用这种类型的代码似乎需要它。

Another alternative might be to create the formula instead of pasting a link:

另一种选择可能是创建公式而不是粘贴链接:

Worksheets(sheetTo).Cells(toRow, toCol).Formula = _
    "=" & Worksheets(sheetFrom).Name & "!" & Worksheets(sheetFrom).Cells(fromRow, fromCol).Address

回答by guitarthrower

I try to stay away from using Select. It can introduce problems in the flow of the code and make things hard to debug later.

我尽量避免使用 Select。它可能会在代码流中引入问题,并使以后难以调试。

Why not try:

为什么不试试:

Worksheets(sheetFrom).Cells(fromRow, fromCol).Copy
Worksheets(sheetTo).Cells(toRow, toCol).Paste Link:=True