在线路上执行excel VBA脚本时遇到同样的问题 行(Target.row)。选择 我已经尝试过选择范围而我只能做但失败了。
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
答案 0 :(得分:0)
这段代码在哪里?在工作表模块中?当您调用单元格或行并且不将表单放在它前面时,它被称为非限定引用。不合格的引用根据代码的位置引用不同的表。在标准模块中,它们引用活动表。在工作表的类模块中,它们引用该表。
如果你的代码在Sheet2的类模块中,那么当Sheet1处于活动状态时,非限定的Rows.Select语句将尝试在Sheet2上选择一行。
最佳做法是仅使用限定参考,并且仅在需要时选择和激活工作表和范围。这是一个例子:
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