简体   繁体   English

Excel VBA选择我的一个子例程中的工作表和范围不起作用

[英]Excel VBA selecting worksheets and ranges in one of my sub routines not working

I keep getting the error, "Select Method of Range Class Failed" and unexpected results from Rows("2:2").Insert 我不断收到错误,“选择范围类失败的方法”和行(“2:2”)的意外结果。

Code below 代码如下

Worksheets("Sheet3").Select

Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove    

Range("D4").Select

First the new row is added to Sheet 1 not sheet 3 and then Range cannot be selected 1004 error. 首先将新行添加到工作表1而不是工作表3,然后无法选择范围1004错误。 I have used this exact script to select other worksheets and ranges without an issue. 我已经使用这个确切的脚本来选择其他工作表和范围没有问题。 I can provide the full file and code for anyone who can help 我可以为任何可以提供帮助的人提供完整的文件和代码

Avoid the use of .Select . 避免使用.Select You may want to see This 你可能想看到这个

Also ensure that your worksheet is unprotected. 还要确保您的工作表不受保护。

Is this what you are trying? 这是你在尝试什么?

Worksheets("Sheet3").Rows(2).Insert Shift:=xlDown, _
CopyOrigin:=xlFormatFromLeftOrAbove    

The code below works, define the Sheet, and not using Select (the first time): 下面的代码工作,定义Sheet,而不是使用Select (第一次):

Dim sht3 As Worksheet

Set sht3 = ThisWorkbook.Sheets("Sheet3")

sht3.Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
sht3.Range("D4").Select

When you are using select you'll always ensure that the particular sheet is active. 当您使用select时,您将始终确保特定工作表处于活动状态。 If not activate it using activate property. 如果没有使用activate属性激活它。 Below is the code that does the work 下面是完成工作的代码

Worksheets("Sheet3").Activate

Worksheets("Sheet3").Select

Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

Range("D4").Select

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

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