简体   繁体   中英

Copy and Paste Filtered rows in VBA

I am trying to copy and paste some rows of a filtered table to a range of cells in Excel. As a filter has been applied, the rows to be copied are now always the same. I am trying to paste the copied rows on to cell O2. I have tried to do it this way:

Dim Rows As Range
Rows = Sheet10.Range("B10:B")
With Rows
    .SpecialCells(xlCellTypeVisible).Copy Destination:=Sheet10.Range("O2")
End With
  End Sub

When doing it this way, I always get error 1004: "Method'Range' of object'_Worksheet' failed". The same error pops when I tried it this way:

Dim Rows As Range
Rows = Sheet10.Range("B10:B")
With Sheet10.Range("B10:B")
    .SpecialCells(xlCellTypeVisible).Copy Destination:=Sheet10.Range("O2")
End With
  End Sub

I am new to VBA and I think I might be missing some basic object rules. Thank you.

  • Range address should be B10:B100 ;
  • Use the Set word, when you set a range;
  • Do not use Rows as a variable word, it is used in VBA;
  • Use Worksheets , not Sheets , it is a bit better;
  • Use Option Explicit on top.

Like this:

Option Explicit

Public Sub TestMe()
    Dim rngRows As Range

    Set rngRows = Worksheets(8).Range("B10:B100")
    With rngRows
        .SpecialCells(xlCellTypeVisible).Copy Destination:=Worksheets(8).Range("O2")
    End With

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM