select范围级别的方法失败

当在行(Target.row)行执行Excel VBA脚本时,我有同样的问题。select我已经尝试select范围,所有我可以做但失败。

Function DoOne(RowIndex As Integer) As Boolean Dim Key Dim Target Dim Success Success = False If Not IsEmpty(Cells(RowIndex, 1).Value) Then Key = Cells(RowIndex, 1).Value Sheets("Sheet1").Select Set Target = Columns(4).Find(Key, LookIn:=xlValues) If Not Target Is Nothing Then Rows(Target.row).Select [- Here it throws "select method of range class failed"-] Selection.Copy Sheets("Sheet2").Select Rows(RowIndex + 1).Select Selection.Insert Shift:=xlDown Rows(RowIndex + 2).Select Application.CutCopyMode = False Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove Cells(RowIndex + 3, 1).Select Success = True End If End If DoOne = Success End Function 

这个代码在哪里? 在工作表模块中? 当您调用“单元格”或“行”时,不要将表单放在它的前面,这称为非限定参考。 根据代码的位置,不合格的引用是指不同的表单。 在标准模块中,它们指的是活动页。 在工作表的类模块中,它们引用该工作表。

如果您的代码位于Sheet2的类模块中,则在Sheet1处于活动状态时,非限定的Rows.Select语句将尝试在Sheet2上select一个行。

最好的做法是只使用合格的参考文献,并且只在需要时才select和激活工作表和范围。 这是一个例子:

 Function DoOne(RowIndex As Long) As Boolean Dim rTarget As Range Dim bSuccess As Boolean Dim sh1 As Worksheet, sh2 As Worksheet Dim rKey As Range bSuccess = False Set sh1 = ThisWorkbook.Worksheets("Sheet1") Set sh2 = ThisWorkbook.Worksheets("Sheet2") Set rKey = sh2.Cells(RowIndex, 1) If Not IsEmpty(rKey.Value) Then Set rTarget = sh1.Columns(4).Find(What:=rKey.Value, LookIn:=xlValues) If Not rTarget Is Nothing Then rKey.Offset(1, 0).EntireRow.Insert rTarget.EntireRow.Copy rKey.Offset(1, 0).EntireRow rKey.EntireRow.Copy rKey.Offset(1, 0).EntireRow.PasteSpecial xlPasteFormats Application.CutCopyMode = False bSuccess = True End If End If DoOne = bSuccess End Function