Search code examples
excelvbaoffice365excel-tableslistobject

Copy filter result if existing


I filter a table for a specific value (in this case "FALSCH") and copy it into another table.

This works, except for the case that there is no cell in the specific column with the value "FALSCH".
Then my code copies the whole content of my table.

ActiveSheet.ListObjects("Tabelle328").Range.AutoFilter Field:=6, Criteria1:="FALSCH"
Range("Tabelle328").Select
Selection.Style = "40 % - Akzent2"
Range("Tabelle328[[GuV Ext. CMIS]:[Kontostand]]").Select
Selection.Copy

Range("O12").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
  :=False, Transpose:=False
ActiveSheet.ListObjects("Tabelle328").Range.AutoFilter Field:=6

Solution

  • Try to declare Option Explicit in every Section. Do not use Select to refer to an entity, but make a direct reference to it. In your case you have to select the cells with the property xlCellTypeVisible, as in the example:

    Option Explicit
    
    Sub Unckown()
       Dim visRng As Range
       ActiveSheet.ListObjects("Tabelle328").Range.AutoFilter field:=6, Criteria1:="FALSCH"
       On Error Resume Next
       Set visRng = Range("Tabelle328").SpecialCells(xlCellTypeVisible)
       On Error GoTo 0
       If Not visRng Is Nothing Then
          'visRng.Style = "40 % - Akzent2"
          Range("Tabelle328[[GuV Ext. CMIS]:[Kontostand]]").Copy
          Range("O12").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
       End If
       ActiveSheet.ListObjects("Tabelle328").Range.AutoFilter field:=6
    End Sub