1

Rows(Target.row).Select の行で 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

このコードはどこにありますか? ワークシート モジュールでは? Cells または Rows を呼び出し、その前にシートを配置しない場合、それは非修飾参照と呼ばれます。非修飾参照は、コードの場所に応じて異なるシートを参照します。標準モジュールでは、アクティブシートを参照します。ワークシートのクラス モジュールでは、そのシートを参照します。

コードが Sheet2 のクラス モジュールにある場合、未修飾の Rows.Select ステートメントは、Sheet1 がアクティブなときに 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
于 2013-08-08T14:11:51.927 に答える