Home » excel » Excel VBA – copying and pasting visible table rows only

Excel VBA – copying and pasting visible table rows only

Posted by: admin March 9, 2020 Leave a comment


I am trying to copy only the visible rows in a table into a seperate worksheet in the same workbook. I’m a little new to using the ‘ListObject’ approach to dealing with tables (for a few reasons, referencing the table directly is a better approach here in terms of the rest of my module)

Below is my best attempt, when I run it I get ‘run-time error ‘438” on the 'Sheets("Sheet8").Range("A1").Paste' line, I’ve been scouring the internet for an hour now trying to figure out what I’m doing wrong, how do I need to re-phrase it so that it pastes the copied data into another sheet/table? Any assistance would be appreciated!



Private Sub CopyVisibleAreaOfTable(ByVal TableName As String)

Const FN_NAME As String = "CopyVisibleAreaOfTable"
On Error GoTo catch

    Dim TargetTable As ListObject
    Dim NumberOfAreas As Long

    Set TargetTable = Sheets("Adj1").ListObjects(TableName)

    ' Check that there are fewer than 8192 seperate areas
    With TargetTable.ListColumns(1).Range
        NumberOfAreas = .SpecialCells(xlCellTypeVisible).Areas(1).Cells.Count
        Debug.Print NumberOfAreas
    End With

    If NumberOfAreas = 0 Then
        'Do something to trigger an error message

        Application.CutCopyMode = False

    End If

    Exit Sub

    Call ErrorReport(FN_NAME, True, Err.Number, Err.Description, "Table Name: " & TableName)
    Resume finally

End Sub
How to&Answers:

Specify the destination as part of the .Copy method:

TargetTable.Range.SpecialCells(xlCellTypeVisible).Copy _