首页 > 解决方案 > 找到 'TargetTable.Range.SpecialCells(xlCellTypeVisible).Copy _ ' 目的地:=Sheets("Sheet8").Range("A1")

问题描述

我有一张名为“Staffdb”的工作表,其中有两个名为“PermTBL”和“StaffTBL”的表,标题相同“Girls”“ID”“Hire_date”和“Status”。所有当前和历史上的员工都在 PermTBL。我想在状态字段上过滤 PermTBL 为“A”表示活动,然后将它们复制到空的 StaffTBL。在使用状态向下箭头手动过滤 PermTBL 并仅选择“A”后,我进入测试代码并获得明显的部分副本。我的代码是选项显式

子 PermTBLtoStaffTBL()

调暗 rgnsrc 作为范围 调暗 rgndest 作为范围

Set rgnsrc = Worksheets("Staffdb").Range("PermTBL")
Set rgndest = Worksheets("Staffdb").Range("StaffTBL")
rgnsrc.SpecialCells(xlCellTypeVisible).Copy rgndest

结束子

最后作为一条附加信息,StaffTBL 似乎有隐藏的行,3-7 不可见,这似乎与我丢失的数据相对应。我试图取消隐藏无济于事。关于下一步去哪里的建议?我必须遍历表格还是在目的地出错?在这方面是新的,第三世界的互联网速度,以及无法交付书籍使得这是一个乏味的过程。请耐心等待 NewBee。

新的信息,我发现如果我取消隐藏整个工作表,正确的数据会出现在 StaffTBL 中,当然 PermTBL 的过滤器也会消失,所以显然我是在正确的轨道上。仍然希望以编程方式(而不是手动)过滤 PermTBL 的意见和建议。我将继续为此搜索网站,但感谢您提出任何建议。

标签: excelexcel-tablesvba

解决方案


Sub CopyData()

    Dim t As ListObject
    Dim t2 As ListObject

    Set t = ActiveSheet.ListObjects("PermTBL")
    Set t2 = ActiveSheet.ListObjects("StaffTBL")

    ' Remove all rows from StaffTBL table
    If Not t2.DataBodyRange Is Nothing Then
        t2.DataBodyRange.Rows.Delete
    End If

    ' Filter Status by "A"
    t.DataBodyRange.AutoFilter Field:=4, Criteria1:="A"
    ' Copy to first cell right below the table's header
    t.DataBodyRange.Copy t2.Range(1).Offset(1)
    ' Remove filter from PermTBL table
    t.DataBodyRange.AutoFilter

End Sub

更新

示例工作簿


推荐阅读