vba - 选择行并删除不会删除行

标签 vba excel

我编写了一些简单的代码,将一个工作表中的单元格与另一个工作表中的单元格进行匹配,然后如果单元格相等则删除整行。

代码正确地选择了行,但出于某种原因拒绝实际删除我的工作表中的行。编辑:一些行删除。其他人则没有,即使它们与确实删除的值具有完全相同的值。如果有人可以提供帮助,我们将不胜感激。

Sub delFunds()
Dim fCell As Range 'Fund cell
Dim fRng As Range 'Fund range
Dim wCell As Range 'Working sheet cell
Dim wRng As Range 'Working sheet range
Dim n As Long

Set fRng = Worksheets("Funds").Range("C2:C117")
Set wRng = Worksheets("Working sheet").Range("I3:I7483")

For Each fCell In fRng.Cells 'Loop through all funds
    For Each wCell In wRng.Cells 'Loop through all working cells
        If StrComp(wCell.Value, fCell.Value, vbTextCompare) = 0 Then 'If equal then delete
            n = wCell.Row
            Rows(n & ":" & n).Select
            Selection.Delete Shift:=xlUp
        End If
    Next wCell
Next fCell 'Go to next fund

End Sub

最佳答案

我会在没有嵌套循环的情况下使用这段代码:

Sub delFunds()
    Dim rngToDel As Range 
    Dim fRng As Range 'Fund range
    Dim wCell As Range 'Working sheet cell
    Dim wRng As Range 'Working sheet range

    Set fRng = Worksheets("Funds").Range("C2:C117")
    Set wRng = Worksheets("Working sheet").Range("I3:I7483")

    For Each wCell In wRng 'Loop through all working cells
        ' if wCell found in Fund range then delete row
        If Not IsError(Application.Match(Trim(wCell.Value), fRng, 0)) Then
            If rngToDel Is Nothing Then
                Set rngToDel = wCell
            Else
                Set rngToDel = Union(rngToDel, wCell)
            End If
        End If
    Next wCell

    If Not rngToDel Is Nothing Then rngToDel.EntireRow.Delete
End Sub

关于vba - 选择行并删除不会删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23088436/

相关文章:

c# - 在 Excel 中打开 .dat(制表符分隔文件),另存为 .xls

python - 如何在Python中使用pandas编写数据数组以在行而不是列中表现出色

vba - Excel 自动过滤除变量值之外的所有值

vba - 使用不一致的分隔符拆分字符串

excel - VBA 中具有多个 IF 和 FOR 语句的 SUMPRODUCT - 错误

VBA Excel : How to assign range of cells to another range of cells?

vba - 使用 VBA 添加计算字段

excel - 调用用户定义的函数

excel - VBA Selenium 循环遍历每个表

excel - 具有多个条件的水平查找