gpt4 book ai didi

excel - 使用 VBA 删除 Excel 表格行

转载 作者:行者123 更新时间:2023-12-04 22:25:49 24 4
gpt4 key购买 nike

我正在尝试删除 TEAMS 的行表当Value2D不匹配变量 department (字符串)。我能够检测到我想要删除的行,但删除方法会导致“delete method of range class failed”错误。

这是一个简化的代码片段。

Dim i As Integer
For i = 1 To wkbook.Worksheets("T").Range("TEAMS").Rows.Count
With wkbook.Worksheets("T").Range("TEAMS[D]")(i)
If .Value2 <> department Then
.EntireRow.Delete
End If
End With
Next i

最佳答案

您在 ListObject/table - 使用 ListObject API。

Dim table As ListObject
Set table = wkbook.Worksheets.ListObjects("TEAMS")

Dim colIndex As Long
Set colIndex = table.ListColumns("D").Index

Dim toDelete As Range

Dim currentRow As ListRow
For Each currentRow In table.ListRows
If currentRow.Range.Cells(ColumnIndex:=colIndex).Value <> department Then
If toDelete Is Nothing Then
Set toDelete = currentRow.Range
Else
Set toDelete = Application.Union(toDelete, currentRow.Range)
End If
Next

If Not toDelete Is Nothing Then toDelete.Delete

非常类似于 this answer .

关于excel - 使用 VBA 删除 Excel 表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57874672/

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