简体   繁体   English

运行时错误“1004”:使用此工作簿选择范围类的方法失败

[英]Run Time Error '1004': Select method of Range Class failed using ThisWorkbook

During the process of running a script if I manually remove focus from the Workbook containing the macro I get the error quoted.在运行脚本的过程中,如果我从包含宏的工作簿中手动删除焦点,我会得到引用的错误。 If I don't click on anything it works without issue.如果我不点击任何东西,它就可以正常工作。 Script errors out only when I'm trying to place selection back into A1 from the "Input" sheet.仅当我尝试将选择从“输入”表重新放入A1时,脚本才会出错。 Break point is on following line:断点在以下行:

ThisWorkbook.Sheets("Input").Range("A1").Select

If I debug and place focus back on macro Worksheet the script completes without issue.如果我调试并将焦点放回到宏工作表上,脚本将毫无问题地完成。 Previous line:上一行:

ThisWorkbook.Sheets("Input").Cells.Delete

runs without error so I'm guessing its the range that is falling out of scope but don't quite understand why as it should be defined by the previous scope notations.运行没有错误,所以我猜测它的范围超出了范围,但不太明白为什么,因为它应该由以前的范围符号定义。 Can someone explain why that line is falling out of scope?有人可以解释为什么这条线超出范围吗? Shouldn't the ThisWorkbook define fairly explicitly the Workbook that my code is referencing?如果不是ThisWorkbook定义相当明确的工作簿,我的代码是引用? Any guidance is greatly appreciated.非常感谢任何指导。

It doesn't have anything to do with the reference to ThisWorkbook at all.它与对ThisWorkbook的引用完全没有任何关系。 You simply can't Select a Range in an object that isn't active.您根本无法在非活动对象中选择范围。 Consider this code, which exhibits the same error:考虑以下代码,它显示了相同的错误:

Private Sub OneOhOhFour()

    'Executing with Book1.xlsm active and Book2.xlsx open.
    Dim wb As Workbook
    Set wb = Application.Workbooks("Book2.xlsx")
    Debug.Print ThisWorkbook.Name
    'Outputs 'Book1.xlsm' to Immediate window.
    wb.Sheets("Sheet1").Range("A1").Select   'Error 1004

End Sub 

Same thing with Worksheets:与工作表相同的事情:

Private Sub OneOhOhFourVTwo()
    'Starting on anywhere but Sheet2 gives an error.
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet2")
    ws.Range("A1").Select  'Error 1004.
End Sub

The simple solution is to Activate the object before you Select within it:简单的解决方案是在选择对象之前激活对象:

Private Sub NoOneOhOhFour()

    Dim wb As Workbook
    Set wb = Application.Workbooks("Book2.xlsx")
    wb.Activate
    wb.Sheets("Sheet1").Range("A1").Select  'No error.

End Sub

Even better is using references and trying to avoid using the Selection and Active* objects entirely.更好的是使用引用并尽量避免完全使用 Selection 和 Active* 对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM