我是VBA的新手,我正在尝试让我的代码在K行中循环大约10,000行整数并根据值删除行,我的代码可以工作,但一次只会做一些小部分。请指教。
'Delete unwanted accounts
Dim Lcell As Long
Application.ScreenUpdating = False
Lcell = TransSheet.Cells(Rows.Count, "K").End(xlUp).Row
For a = 1 To Lcell Step 1
Select Case Cells(a, 11).Value
Case "1200", "652", "552"
Cells(a, 11).EntireRow.Delete
End Select
Next a
Application.ScreenUpdating = True
答案 0 :(得分:2)
您可以对所有已识别的行执行单个删除:
'Delete unwanted accounts
Dim rngDel as range
Dim Lcell As Long, v
Lcell = TransSheet.Cells(Rows.Count, "K").End(xlUp).Row
For a = 1 To Lcell
v = Cells(a, 11).Value
If v = "1200" or v = "652" or v = "552" Then
If Not rngDel is Nothing Then
Set rngDel = Application.Union(rngDel, Cells(a, 11).EntireRow)
Else
Set rngDel = Cells(a, 11).EntireRow
End If
End If
Next a
If Not rngDel Is Nothing Then rngDel.Delete
答案 1 :(得分:0)
从最后一行尝试到第一行。您正在删除行,因此您的编号将被删除:
'Delete unwanted accounts
Dim Lcell As Long
Application.ScreenUpdating = False
Lcell = TransSheet.Cells(Rows.Count, "K").End(xlUp).Row
For a = Lcell To 1 Step -1
Select Case Cells(a, 11).Value
Case "1200", "652", "552"
Cells(a, 11).EntireRow.Delete
End Select
Next a
Application.ScreenUpdating = True
答案 2 :(得分:0)
将此行添加到您的代码中
Cells(a, 11).EntireRow.Delete
a = a - 1
这将处理由于行消失而发生的移位。
另外,我个人使用以下方法删除多行。例如我要删除的行存储在Variant
数组DelRows()
中。您可以在运行时动态获取它们。在这里,我手动分配一些随机行。
Sub DeleteRows()
Dim DelRows() As Variant
ReDim DelRows(1 To 3)
DelRows(1) = 15
DelRows(2) = 18
DelRows(3) = 21
'--- How to delete them all together?
Dim i As Long
For i = LBound(DelRows) To UBound(DelRows)
DelRows(i) = DelRows(i) & ":" & DelRows(i)
Next i
Dim DelStr As String
DelStr = Join(DelRows, ",")
' DelStr = "15:15,18:18,21:21"
ActiveSheet.Range(DelStr).Delete
End Sub