gpt4 book ai didi

VBA - 删除 ActiveSheet.UsedRange.Rows.Count 中的空行

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

我的工作表上有大约 50 行,我正在使用 VBA 宏对其进行编辑。
当我以以下格式存储最后使用的行时

NewLastRow = ActiveSheet.UsedRange.Rows.Count

NewLastRow 得出了第 65 行,尽管这些行中没有任何内容。
因此,我合并了一段代码来选择事件范围,并删除没有内容的行。

ActiveSheet.UsedRange.Select

'Deletes the row within the selection if the row has no data.
Dim i As Long

'Turn off aspects which could slow down process.
With Application
.Calculation = xlCalculationManual
.ScreenUpdating = False

'Delete backwards.
For i = Selection.Rows.Count To 1 Step -1
If WorksheetFunction.CountA(Selection.Rows(i)) = 0 Then
Selection.Rows(i).EntireRow.Delete
End If
Next i

.Calculation = xlCalculationAutomatic
.ScreenUpdating = True
End With

这可行,但是需要很长时间。我怎样才能加快速度?

最佳答案

您可以在代码中改进两件事:

1) 您正在迭代所有行。 Excel 2007+ 中的迭代次数超过 100 万次。通常,非空行不超过几千个。因此,如果您首先找到最后一个非空行的索引,然后在 For ... Next 循环中使用该索引作为限制,则代码的运行速度会更快。

2) 删除行是相当耗时的操作,因此如果可能的话应该将其合并为单个操作g。您可以使用 Union 函数将所有要删除的行收集到一个范围中,然后使用单个命令删除所有行。

下面是实现您的任务的完整代码:

Public Sub deleteRows()
Dim wks As Excel.Worksheet
Dim rng As Excel.Range
Dim row As Long
Dim lastRow As Long
'-------------------------------------------------------------------------


Set wks = Excel.ActiveSheet
lastRow = lastNonEmptyRow(wks)


With wks

For row = 1 To lastRow
If Application.WorksheetFunction.CountA(.Rows(row)) = 0 Then

If rng Is Nothing Then
Set rng = .Rows(row)
Else
Set rng = Excel.Union(rng, .Rows(row))
End If

End If
Next row

End With



'In order to avoid Run-time error check if [rng] range is not empty, before removing it.
If Not rng Is Nothing Then
Call rng.EntireRow.Delete
End If



End Sub

注意。为了使此代码正常工作,您需要包含 function to find the last non-empty row in Excel worksheet到您的代码中。

关于VBA - 删除 ActiveSheet.UsedRange.Rows.Count 中的空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31606534/

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