gpt4 book ai didi

excel - 根据每行多个单元格中的值删除行

转载 作者:行者123 更新时间:2023-12-04 20:53:27 27 4
gpt4 key购买 nike

下面的功能代码是根据本网站上的答案拼凑而成的。

我觉得它没有它应该的那么优雅。

代码的目的是检查每行中五个单元格的范围,如果这些单元格中没有正值,则删除该行。

Sub DeleteRowtest()
Dim lr As Integer ' are any of these dims redundant or unnecessary? Incorrect?
Dim cval As Variant
Dim ArrCt As Integer
Dim val As Variant

'the initial redim is there on purpose
' instead of ValArray as Variant then ValArray = array().
' this seems cleaner but which is better?
ReDim ValArray(0) As Integer

Dim T As Boolean

lr = Cells(Rows.Count, 11).End(xlUp).Row
For i = lr To 2 Step -1
ArrCt = 0

'this loop appears to work the way I want,
' but am I using .cells and .value correct here?
For Each cval In Range(Cells(i, 5), Cells(i, 10)).Cells
ValArray(ArrCt) = cval.Value
ArrCt = ArrCt + 1
ReDim Preserve ValArray(ArrCt)
Next

'is there a cleaner way than this array and nested loop
' to determine the same info and act on it?
' (i.e. if all values of cell range are <1 delete row)
For Each val In ValArray
If val > 0 Then
T = True
End If
Next

If T = False Then Rows(i & ":" & i).EntireRow.Delete
T = False
Next

'finally, are there any errors/broken logic at all here that I dont see?

Range("B2").Select
End Sub

最佳答案

我看不出将数据复制到数组并在检查值之后循环数组有任何优势。
我也会小心使用 integer键入,因为它只有 -32 768 到 32 767。Long我认为使用起来更安全。
当您引用单元格/范围时,使用工作簿/工作表直接指向您想要的位置。
例如 Cells(Rows.Count, 11).End(xlUp).Row指当前事件的工作表,这可能不是有意的。

所以这是我的版本

Option Explicit

Sub DeleteRowtest()
Dim LastRow As Long, i As Long
Dim Found As Boolean
Dim Ws As Worksheet
Dim aCell As Range

'turn off screen updating and sheet calculation to improve speed
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Set Ws = ThisWorkbook.Sheets("Your sheet name") 'set reference to sheet

With Ws 'all references starting with "." from now on will refer to sheet "Ws"
LastRow = .Cells(.Rows.Count, 11).End(xlUp).Row 'Find last row

For i = LastRow To 2 Step -1 'loop rows from last to 2
Found = False 'reset variable
For Each aCell In .Range(.Cells(i, 5), .Cells(i, 10))
If aCell.Value > 0 Then ' this will be true also for text in cells
'if you want to check for numeric values only you can try this
' If aCell.Value > 0 And IsNumeric(aCell.Value) Then
Found = True
Exit For
End If
Next aCell
If Not Found Then 'no positive value found in row
.Rows(i & ":" & i).EntireRow.Delete
End If
Next i
.Range("B2").Select
End With

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub

关于excel - 根据每行多个单元格中的值删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52956656/

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