vba - 这些 VBA 代码有什么错误?

标签 vba excel

我的任务是,如果 K 列的值为零,我必须删除整个行。我首先想到的是循环,但我有 4000 行,而 1000 行的 K 值可能为零。

Sub DeleteRowWithContents()
       Last = Cells(Rows.Count, "D").End(xlUp).Row
       For i = Last To 1 Step -1
           If (Cells(i, "K").Value) = 0 Then
              Cells(i, "A").EntireRow.Delete
           End If
       Next i
End Sub

我相信人们会说“它需要时间”,因为它是循环的。这就是为什么我认为最好采用下一个方法,人们还告诉我“查找”比循环快得多。所以我使用了下面的代码,这是我在谷歌搜索时发现的

Sub Delete_zeros()
    Dim rCell As Range
    Dim strAddress As String
Application.ScreenUpdating = False
ThisWorkbook.Sheets(1).Activate
    With ActiveSheet.Columns("K")
        Set rCell = .Find(What:=0, LookIn:=xlValues, SearchOrder:=xlByColumns)
        If Not rCell Is Nothing Then
            Do
            strAddress = rCell.Address
            rCell.EntireRow.Delete
            Set rCell = .FindNext(Range(strAddress))
            Loop Until rCell Is Nothing
        End If
    End With
Application.ScreenUpdating = True
End Sub

但是我发现上面的代码,如果 k 列中有 10 或 20 值,它也会删除该行。我的意思是,如果数字包含零,则将其删除

示例。

    204 or 200 or 205 or 301 or 10 \ Its deleting all these rows

这些代码有什么问题吗?这些代码比我想要使用的循环太快,但我发现了它的错误。

请解释该错误的原因。如果 K 列中的值为零而不是循环或(也可能循环应该太快),那么对其他方法有什么帮助,该方法可以更快地删除行?我们将不胜感激。谢谢

最佳答案

不是bug,在find方法中添加这个参数

LookAt:= xlwhole

要使用过滤器,请执行以下操作

Sub FilterAndDelete()
'Developer by Bruno Leite
'http://officevb.com 

    Dim Sht As Worksheet
    Dim FilterRange As Range
    
    'Set your Sheet
    Set Sht = ThisWorkbook.Sheets("Plan2")
    
    'Verify if is Filter
    If Sht.FilterMode Then
      Sht.ShowAllData
    End If
    
    'Filter Column A with 0 at parameter
    Sht.Range("A:A").AutoFilter Field:=1, Criteria1:="0"
    
    'Define Range Of Visible cells without row title
    Set FilterRange = Sht.Range("A1").CurrentRegion.Offset(1, 0).SpecialCells(xlCellTypeVisible)
       
    Application.DisplayAlerts = False
    
    FilterRange.Rows.Delete
    
    Application.DisplayAlerts = True
        
    Sht.ShowAllData
    
End Sub

关于vba - 这些 VBA 代码有什么错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7282132/

相关文章:

vba - Excel VBA 数据透视表显示详细信息

vba - 打开新工作簿 Excel 2016 VBA 后功能区无响应

excel - 如何在Excel中获取表格上方的单元格的值

sql - 使用 VBA 将 Excel 表连接到 SQL Server

Excel浮点精度 "ROUND()"hack不起作用

vba - Rows.Count 方法在 Excel VBA 中运行不佳(尽管我指定了获取行数的工作表,但它在错误的工作表中获取行数。)

VBA - (Excel) 为什么我不能在不出现类型不匹配错误的情况下为用户窗体设置文本框类型?

csv - 用于将三个 csv 文件列合并为一列的 Windows 脚本

excel - 如何使用 Excel::Writer::XLSX 自动调整列宽

java - Oracle ODI 字符串文字映射