如何在VBA中使用SpecialCells(xlCellTypeVisible)仅从范围中选择行?

时间:2020-06-29 12:53:42

标签: excel vba userform

我正在尝试从表中复制已过滤的数据并将其粘贴到另一个工作簿中。到目前为止,该过程仍然有效,但是复制数据的行数大于范围的实际行数。似乎正在对复制的过滤后的表格中每一列的行进行计数,因为当我粘贴值时,我还会看到其他空行。

我尝试了.DataBodyRange.SpecialCells(xlCellTypeVisible).Rows.Count,但给了我错误。关于“该范围无法正常运行,因为它与现有表格不符...”

 'Filter the data based on the field and criteria
    With SourceListObject
        If Not Id = "" Then
            .Range.AutoFilter Field:=2, Criteria1:=Id
        End If
        
        'Get the total visible cell count after filtering
        SourceDataRowsCount = .DataBodyRange.SpecialCells(xlCellTypeVisible).Count

    End With
    
    
    'Copy the filtered data to the table
    With DestListObject
        'Get the count of the rows in the table (starts with 2 empty rows - need to figure out a way to either
        'have no row and add to the table or delete the rows after adding values to the rows
        'Then set the size of the range based on the source range count
        TargetDataRowsCount = .DataBodyRange.Rows.Count
        .Resize .Range.Resize(SourceDataRowsCount, .Range.Columns.Count)
        
        'Paste the values in the first row
        SourceListObject.DataBodyRange.SpecialCells(xlCellTypeVisible).Copy
        .DataBodyRange.Cells(1, 1).PasteSpecial xlPasteValues
        
    End With
    
    
    'Clear the filter
    With SourceListObject
    
        .Range.AutoFilter Field:=2
        
    End With

我看到像这样的空行。这是来自虚构数据:

enter image description here

我在做什么错了?

0 个答案:

没有答案
相关问题