运行时错误'91'用于将行复制到另一个工作表

时间:2018-05-17 16:34:21

标签: vba excel-vba excel

Sub retrieve()

Dim r As Long, endrow As Long, pasterowindex As Long, Cells() As String, Columns As Range

Sheets("Raw Trade Log").Range("A4").Select
Selection.End(xlDown).Select: endrow = ActiveCell.Row

pasterowindex = 1

For r = 4 To endrow
    If Cells(r, Columns(17).Value = "Y") Then

        Rows(r).Select
        Selection.Copy

        Sheets("Completed Trade log").Select
        Rows(pasterowindex).Select
        ActiveSheet.Paste

        pasterowindex = pasterowindex + 1

        Sheets("Raw Trade Log").Select
    End If
Next r


End Sub

我试图告诉vba在列中的值变为“Y”时自动将整行复制到另一张表但是我一直在

  

运行时错误'91'

来自If Cells(r, Columns(17).Value = "Y") Then并且我不知道如何修复它,有人可以让我知道我在哪里犯了错误吗?

2 个答案:

答案 0 :(得分:1)

错误主要是因为SelectActivate字。这些都不是编程友好的,人们应该小心它们。因此,最好的方法是完全避免它们 - How to avoid using Select in Excel VBA

关于“如何将某些条件下的行复制到另一个工作表”的任务,这是一个小例子,没有SelectActivate

Sub TestMe()

    Dim wksTarget As Worksheet: Set wksTarget = Worksheets(1)
    Dim wksSource As Worksheet: Set wksSource = Worksheets(2)
    Dim r As Long

    For r = 4 To 50
        If wksSource.Cells(r, "A") = "y" Then 
            wksSource.Rows(r).Copy Destination:=wksTarget.Rows(r)
        End If
    Next r

End Sub
  • 50是硬编码的,也可以称为变量;
  • 代码检查列y中的单词A,但可以通过将A中的If wksSource.Cells(r, "A")更改为相应的内容来更改。

答案 1 :(得分:0)

你可以使用AutoFilter():

Sub retrieve()
    With Sheets("Raw Trade Log") 'reference your "source" sheet
        With .Range("A3", .Cells(.Rows.Count, 1).End(xlDown)).Offset(, 16) ' reference referenced sheet column Q cells from row 3 (header) down to column A last not empty row
            .AutoFilter Field:=1, Criteria1:="y" ' filtere referenced column with "y" content
            If Application.Subtotal(103, .Cells) > 1 Then .Resize(.Rows.Count - 1, .Columns.Count).Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Copy Destination:=Sheets("Completed Trade log").Range("A1") ' if any filtered cell other than header, copy filtered cells entire row to "target" sheet
        End With
        .AutoFilterMode = False
    End With
End Sub