1

在行(Target.row)行执行 excel VBA 脚本时,我遇到了同样的问题。选择我已经尝试选择范围,我能做的一切但失败了。

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
4

1 回答 1

0

Where is this code? In a worksheet module? When you call Cells or Rows and don't put the sheet in front of it, it's called an unqualified reference. Unqualified references refer to different sheets depending on where the code is. In a standard module, they refer to the activesheet. In a worksheet's class module, they refer to that sheet.

If your code is in Sheet2's class module, then the unqualified Rows.Select statement will try to select a Row on Sheet2 when Sheet1 is active.

The best practice is to only use qualified references and to only select and activate sheets and ranges when you need to. Here's an example:

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
于 2013-08-08T14:11:51.927 回答