gpt4 book ai didi

vba - Excel VBA 从单元格中删除内容然后删除总行数

转载 作者:行者123 更新时间:2023-12-03 02:27:19 29 4
gpt4 key购买 nike

我正在编程检查一个范围,从单元格范围中删除内容,然后删除已清除内容的整行单元格。目前,我运行代码,所有行都被删除。另外,我很欣赏使代码干燥的建议。

Option Explicit

Sub Alfredo()

Dim msg As String
Dim VarCase As Range
Dim ws As Worksheets

Set ws = Sheets("Data")

For Each VarCase In ws.Range("D1:D11000")
If VarCase.Value2 = "John" Or VarCase.Value2 = "Thompson" Or VarCase.Value2 =
"Mattson" Then
VarCase.ClearContents
End If
Next VarCase

For Each VarCase In ws.Range("D1:D11000")
If VarCase.Value = "" Then
Rows.EntireRow.Delete
End If
Next VarCase

End Sub

最佳答案

在最后的 For 循环中,您有

Rows.EntireRow.Delete

你应该在哪里

VarCase.EntireRow.Delete

这可能是一般删除的原因。

For Each 构造并不总是能很好地处理正在更改的范围(此处为行删除),因此请注意这一点。您可能会通过 Union 累积一系列删除目标,并在最后的一条语句中删除以实现 DRYness,而无需清除任何内容。

此外,缩进是你的 friend 。

<小时/>

编辑以添加 Union 方法的说明:

Sub TestRowDelete()
Dim ARange As Range
Dim DRange As Range

Set DRange = Nothing

For Each ARange In ActiveSheet.UsedRange.Rows
If ARange(1).Value = "d" Then ' testing first cell on each row
If DRange Is Nothing Then
Set DRange = ARange
Else
Set DRange = Union(DRange, ARange)
End If
End If
Next ARange

If Not DRange Is Nothing Then DRange.EntireRow.Delete

End Sub

关于vba - Excel VBA 从单元格中删除内容然后删除总行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46186443/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com