1004对象“ _Worksheet”的方法“ Range”无法引用另一个工作表

时间:2019-03-16 02:14:41

标签: excel vba

我看过很多标题相似的问题,但似乎没有一个匹配我的问题。

下面的代码段来自我已经运行多年没有任何问题的初始化例程。它仅设置变量值,并且不更改任何单元格,而是由其他例程调用以设置所需的Public变量。

到目前为止,当工作表的代号wsPlan处于活动状态时,始终会调用它。我目前正在另一张纸上的工作簿中添加功能,其中一个按钮将启动子例程。我尚未使用该按钮,仅从该工作表开始进行测试。当我在其他工作表处于活动状态时调用此例程时,在1004行上出现Set StatusFilterIndicator错误,但在Set SpecViewIndicator行上没有错误。

Cells行和列号最初是变量,因此我将它们更改为它们的值以检查是否有问题,但没有更改。我也重新启动,以防万一,但是没有。但是,如果我在调用例程之前激活wsPlan,则不会出错。现在,这是我的解决方法,但我不喜欢这样。

两行之间的唯一区别是使用Range,因为这是两个单元格。我认为没有任何理由应该有所作为,并且在wsPlan处于活动状态时,这运行得很好。我想念什么?

Public Sub TableInfo

   Public SpecViewIndicator As Range
   Public StatusFilterIndicator As Range
   .
   .
   .
   Set SpecViewIndicator = wsPlan.Cells(1, 22)
   Set StatusFilterIndicator = wsPlan.Range(Cells(1, 25), Cells(2, 25))

2 个答案:

答案 0 :(得分:2)

您还需要限定单元格。如果wsplan未激活,则范围将适用于两张纸,因此会出现错误。

With wsPlan 
    Set StatusFilterIndicator = .Range(.Cells(1, 25), .Cells(2, 25))
End With

答案 1 :(得分:2)

两个单元格都必须明确具有与Range相同的父工作表。

'in your code, Cells belong to whatever is the worksheet in the foreground (i.e. the ActiveSheet)
'while Range explicitly belongs to the wsPlan worksheet
'this only works if wsPlan is the ActiveSheet
Set StatusFilterIndicator = wsPlan.Range(Cells(1, 25), Cells(2, 25))

'you need to ensure they all belong to wsPlan
Set StatusFilterIndicator = wsPlan.Range(wsPlan.Cells(1, 25), wsPlan.Cells(2, 25))

'you can shorthand that code by incorporating  With ... End With block
'this is also more efficient as wsPlan is only 'loaded' once
With wsPlan
    Set StatusFilterIndicator = .Range(.Cells(1, 25), .Cells(2, 25))
End With

请注意,.Range和两个.Cells都有一个前缀周期(.)。这就是从With ... End With块捕获父对象的过程。就像您只是从wsPlan.RangewsPlan.Cells中取出wsPlan(离开句点),然后将其移至With ... End With包装器中一样。