gpt4 book ai didi

excel - 删除电子表格中行的有效方法

转载 作者:行者123 更新时间:2023-12-04 21:25:47 26 4
gpt4 key购买 nike

有没有比我目前使用的更好的方法来删除 Excel 电子表格中的行?

在电子表格上,我运行一个宏,如果特定单元格中的数字为“0”,则删除一行。

Public Sub deleteRowsIfZero(colDelete As Integer)
Dim r As Long
Application.ScreenUpdating = False

For r = Cells(Rows.Count, colDelete).End(xlUp).Row To 1 Step -1
If Cells(r, colDelete).Value = "0" Then Rows(r).Delete
Next r
Application.ScreenUpdating = True
End Sub

这行得通,但是对于 700 多行的电子表格,它可能会很慢。有没有更有效的方法来做到这一点?

提前感谢您的任何建议。

干杯

诺埃尔

最佳答案

我会使用一个连续的范围并一次性删除它:

Public Sub deleteRowsIfZero(strSeekValue As String)
Dim lngRowsToDelete() As Long
Dim strRowsToDelete() As String
Dim x As Long, y As Long, n As Long, z As Long

On Error GoTo err_

'get the extent of the workbook range
x = Me.UsedRange.Rows.Count

n = -1

'switch off screen updating and calculation
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

'starting from row 1, look for the strSeekValue in column A, keep going till x is reached
For y = 1 To x
If Me.Range("A" & y).Value = strSeekValue Then 'if we find one, pop the row number into the array
n = n + 1
ReDim Preserve lngRowsToDelete(0 To n)
lngRowsToDelete(n) = y
End If
Next y

'if none were found, don't do the next bit
If n = -1 Then GoTo err_

'create a string of all the rows we found
z = 0
ReDim strRowsToDelete(z)
For y = 0 To n
strRowsToDelete(z) = strRowsToDelete(z) & lngRowsToDelete(y) & ":" & lngRowsToDelete(y) & ","
If Len(strRowsToDelete(z)) > 240 Then 'As A.Webb points out, the 255 limit will be a problem here
strRowsToDelete(z) = Left(strRowsToDelete(z), Len(strRowsToDelete(z)) - 1) 'drop the trailing comma
z = UBound(strRowsToDelete) + 1 'resize the array
ReDim Preserve strRowsToDelete(0 To z)
End If
Next y

For y = z To 0 Step -1
If Right(strRowsToDelete(z), 1) = "," Then strRowsToDelete(z) = Left(strRowsToDelete(z), Len(strRowsToDelete(z)) - 1)
'now delete the rows
Me.Range(strRowsToDelete(y)).EntireRow.Delete
Next y

err_:
'assumes calculation was set to auto
Application.Calculation = xlCalculationAutomatic
If Err Then Debug.Print Err.Description
Application.ScreenUpdating = True
End Sub


'run sub foo
Sub foo()
deleteRowsIfZero "0"
End Sub

关于excel - 删除电子表格中行的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13234009/

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