从其他工作表运行表单代码时出错

时间:2018-10-03 22:45:37

标签: excel-vba

我有一个包含许多订阅的表格。工作簿有很多工作表。当我在活动工作表为CodesSheet时启动窗体时,使用下面代码中的任何For Each rCell都可以。当我从另一张纸开始代码时,使用第二行-.Range("L2:L4125")-时代码运行正常,但第一行-.Range(Cells(2, 12), Cells(LastRowCodes, 12))失败。

消息为Run time error 1004 - Method Range of object _worksheet failed。但是在调试时,将鼠标悬停在LastRowCodes上会显示正确的值(4125)。

任何人都能发现错误吗?

For Each rCell In CodesSheet.Range(Cells(2, 12), Cells(LastRowCodes, 12)) '-->Error here, although LastRowCodes is correct
'For Each rCell In CodesSheet.Range("L2:L4125") '--> If using this instead of the above, no error

    'Do Stuff

Next rCell

1 个答案:

答案 0 :(得分:1)

Cells如果没有Worksheet引用,则表示假设为ActiveSheet

使用With...End With块完全符合Worksheet的条件-请注意句点。

With CodesSheet
    For each rCell in .Range(.Cells(2, 12), .Cells(LastRowCodes, 12))
        ....
    Next rCell
End With
相关问题