Excel 选择范围类的方法失败

Excel 选择范围类的方法失败,excel,vba,Excel,Vba,在第行执行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 She

在第行执行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

代码在哪里?在工作表模块中?当调用单元格或行时,如果不将工作表放在前面,则称为非限定引用。不合格参考文件指的是不同的表格,具体取决于代码所在的位置。在标准模块中,它们指的是活动表。在工作表的类模块中,它们引用该工作表

如果代码位于Sheet2的类模块中,则当Sheet1处于活动状态时,非限定行.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

你有没有仔细检查过代码,看看当它出错时,你的目标变量是否有值?RowIndex是否有值?是否在未选择行的情况下尝试了它?类似于
工作表(“Sheet1”).Rows(Target.Row)。复制
。当然,这是假设您的
Find
对象工作正常。请参阅我的答案之一。如果可能,您应该避免选择行,因为它有时会导致不可预测的错误。