【问题标题】:VBA Autofilter - Removing Visible Cells (seems code should work, but doesn't)VBA Autofilter - 删除可见单元格(似乎代码应该工作,但没有)
【发布时间】:2019-07-12 21:38:29
【问题描述】:

我在使用 VBA 删除某些行时遇到了一些麻烦。

我在 A - K 列中按行组织数据。在 K 列中有一个计数器;当它超过 1 时,需要删除整行。我设置了以下代码;并期望它在 K 列上过滤超过 1 的任何内容。如果它发现有超过 1 行(第 1 行是标题),它将删除任何可见的内容,否则它只是从过滤器中删除条件。

但是,第一个消息框返回值 2,900(正确)然后第二个消息框返回值 1,我不知道为什么。因此,K 列超过 1 的行(大约有 2,000 行)都不会被删除。

Visible Rows 在宏的开头定义为 Long。

        With MySheet

        'Find new lastrow
        lRowDbMsNew = .Cells.Find(What:="*", _
            After:=Range("A1"), _
            LookAt:=xlPart, _
            LookIn:=xlFormulas, _
            SearchOrder:=xlByRows, _
            SearchDirection:=xlPrevious, _
            MatchCase:=False).ROW

        .Range("A:K").Calculate

        MsgBox ("The last row in the data is " & lRowDbMsNew)

        .Range("A1:A" & lRowDbMsNew).AutoFilter Field:=11, Criteria1:=">1"

            VisibleRows = .Range("A1:A" & lRowDbMsNew).SpecialCells(xlCellTypeVisible).Rows.Count

            MsgBox ("Number of visible rows: " & VisibleRows)

            If VisibleRows > 1 Then

                .Range("A2:A" & lRowDbMsNew).SpecialCells(xlCellTypeVisible).EntireRow.Delete
                .Range("A1:K" & lRowDbMsNew).AutoFilter Field:=11

                Else

                .Range("A1:K" & lRowDbMsNew).AutoFilter Field:=11

            End If

        End With

【问题讨论】:

  • 3 个想法 - 1) 将自动计算设为 True。并且不要把它变成假的,这是非常危险的。 2) 确保代码中没有On Error Resume Next。 3) 阅读如何调试 - stackoverflow.com/questions/50189158/…
  • 谢谢,我会尝试在计算设置为自动的情况下运行它,宏使用手动,否则运行需要很长时间。因此 (.Range("A:K").Calculate)。有一些 On Error resume Next 但我删除了它们。
  • 如果运行自动计算需要很长时间,那么您应该考虑重写整个应用程序。架构中有问题。
  • 这绝对是真的,但不幸的是,我的 VBA 技能还不足以重构整个事情以始终遵循最佳实践。目前,妥协是可控的!

标签: excel vba


【解决方案1】:

将计算可见行数的行更改为

VisibleRows = .Range("A1:A" & lRowDbMsNew).SpecialCells(xlCellTypeVisible).Count

(删除.rows)。
.SpecialCells-函数返回一个非连续的Range(在您的情况下,包含A 列中可见的所有单元格),例如$A$1,$A$4:$A$6...
如果您检查该范围的Rows-属性(它本身也是Range),您将获得相同的地址,但是,使用Count-属性仅返回第一个所谓的Area 的范围。

用这段cde检查一下:

Dim r As Range
Set r = ThisWorkbook.Sheets(1).Range("A1:A" & lRowDbMsNew).SpecialCells(xlCellTypeVisible)
Debug.Print r.Address
Debug.Print r.Count
Dim r2
Set r2 = r.Rows
Debug.Print r2.Address
Debug.Print r2.Count

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    相关资源
    最近更新 更多