运行时错误"1004":使用ThisWorkbook的范围类的选择方法失败 [英] Run Time Error '1004': Select method of Range Class failed using ThisWorkbook

查看:187
本文介绍了运行时错误"1004":使用ThisWorkbook的范围类的选择方法失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行脚本的过程中,如果我从包含宏的工作簿中手动删除焦点,则会收到引用的错误.如果我不单击任何按钮,它将毫无问题地起作用.仅当我尝试将选择从输入"表放回A1时,脚本才会出错.断点在以下行:

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. 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

运行时没有错误,所以我猜测它的范围不在范围内,但不太了解为什么要由先前的范围符号定义. 有人可以解释为什么这条线不在范围内吗? ThisWorkbook是否应该相当明确地定义我的代码所引用的工作簿?任何指导都将不胜感激.

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? Any guidance is greatly appreciated.

推荐答案

ThisWorkbook的引用完全没有关系.您根本无法在非活动对象中选择范围.考虑下面的代码,它显示出相同的错误:

It doesn't have anything to do with the reference to ThisWorkbook at all. 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 

与工作表相同:

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

更好的方法是使用引用,并尝试避免完全使用Selection和Active *对象.

Even better is using references and trying to avoid using the Selection and Active* objects entirely.

这篇关于运行时错误"1004":使用ThisWorkbook的范围类的选择方法失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆