简体   繁体   English

Excel VBA-简化记录的代码时出现运行时错误1004

[英]Excel VBA - runtime error 1004 when simplifying recorded code

I've got a recorded macro that I tried to simplify by getting a number of activate and select statements onto a single line, but that results in a runtime error. 我有一个记录的宏,我试图通过在一行上添加许多Activate和Select语句来简化这些宏,但这会导致运行时错误。

This is not a critical problem, but I'm just curious to understand what is going on. 这不是一个关键问题,但是我很好奇了解发生了什么。 This is my initial code snippet (it is preceded by a Copy snippet in the procedure): 这是我的初始代码段(在过程中前面有一个复制代码段):

ThisWorkbook.Activate  
Sheets("MS Act Report").Select  
Range("G1").Select  
ActiveSheet.Paste  

this is my simplified code: 这是我的简化代码:

ThisWorkbook.Activate  
Sheets("MS Act Report").Range("G1").Select  
ActiveSheet.Paste    

When running this I get a 运行时,我得到一个

runtime error '1004': Select method of Range class failed

You can only select ranges on the active sheet. 您只能在活动工作表上选择范围。 If "MS Act Report" is not the active sheet, you can't issue a .select command against its cells. 如果“ MS Act报告”不是活动工作表,则不能对其单元格发出.select命令。 To simplify the code, instead of copy-pasting, just make the ranges equal. 为了简化代码,而不是复制粘贴,只需使范围相等即可。

Thisworkbook.WorkSheets("MS Act Report").Range("G1:I5").Value= _
  ActiveWorkbook.Worksheets("Whatever").Range("a1:c5").Value

Some recommended reading: How to avoid using select 一些建议阅读: 如何避免使用select

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

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