gpt4 book ai didi

excel - 代码不删除每个非数字行

转载 作者:行者123 更新时间:2023-12-03 02:39:42 26 4
gpt4 key购买 nike

我这里有这段代码,它查看一列数字,用数字为单元格着色,如果它是非数字条目(单元格用“-”填充),则删除单元格及其相应的行。它删除一些非数字行,但不是全部。

Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet, wsO As Worksheet
Dim iCounter As Long
Dim iCounter1 As Long
Dim iCounter2 As Long
Dim lrow As Long, rw As Long
Dim OutLookApp As Object
Dim OutLookMailItem As Object
Dim MailDest As String
Dim subj As String
Dim bod As String
Dim lastrow As Long
Dim lastrow1 As Long

lastrow = wsI.Cells(Rows.Count, 4).End(xlUp).Row
lastrow1 = wsO.Cells(Rows.Count, 4).End(xlUp).Row

With wsO
For iCounter1 = 2 To lastrow
If wsO.Cells(iCounter1, 9) > 120 Then

wsO.Cells(iCounter1, 9).Interior.Color = RGB(255, 101, 101)

ElseIf wsO.Cells(iCounter1, 9) > 0 And wsO.Cells(iCounter1, 9) < 120 Then

wsO.Cells(iCounter1, 9).Interior.Color = RGB(169, 208, 142)

End If
Next iCounter1

With wsO
For iCounter2 = 2 To lastrow

If Not IsNumeric(Cells(iCounter2, 9)) Then
wsO.Cells(iCounter2, 9).EntireRow.Delete
End If

Next iCounter2


Rows("2:200").RowHeight = 30
End With
End With

最佳答案

您的代码似乎有两个问题。跳过一些应该删除的行的主要问题可以通过从底部到顶部循环来解决。如果无法以这种方式工作,可能意味着删除一行后会跳过一行,对行重新编号,然后递增到下一行。

还有一个次要问题,您已实现 With ... End With statement引用要执行操作的工作表,然后在引用单元格/范围/行时重申工作表引用,或者完全丢弃它。

With wsO
For iCounter1 = 2 To LastRow
If .Cells(iCounter1, 9) > 120 Then
.Cells(iCounter1, 9).Interior.Color = RGB(255, 101, 101)
ElseIf .Cells(iCounter1, 9) > 0 And .Cells(iCounter1, 9) < 120 Then
.Cells(iCounter1, 9).Interior.Color = RGB(169, 208, 142)
End If
Next iCounter1

'this is the primary change
'loop from the bottom to the top when deleting rows
For iCounter2 = LastRow To 2 Step -1
If Not IsNumeric(.Cells(iCounter2, 9)) Then
.Cells(iCounter2, 9).EntireRow.Delete
End If
Next iCounter2

.Rows("2:200").RowHeight = 30
End With

请注意,Cells 变为 .CellsRows 变为 .Rows。句点(又名 .句号`)前缀将每个单元格/范围/行与 With ... End With block 中引用的父工作表相关联。

<小时/>

1 感谢Scott Craner用于注释注释中从下到上的方法。

关于excel - 代码不删除每个非数字行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33767306/

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