#excel #vba
#excel #vba
Вопрос:
Я хочу удалить всю строку на основе содержимого ячейки в этой строке.
Ячейка содержит формулу, которая преобразуется либо в 1, либо в ноль. Следует удалить строку, если 1.
Приведенный ниже код удаляет каждую строку, независимо от того, что находится в AB.
Sub Delete()
Dim FoundCell As AB
Set FoundCell = Worksheets("PM2CORRELATED").Range("AB4:AB1500").Find(what:=1)
Do Until FoundCell Is Nothing
FoundCell.EntireRow.Delete
Set FoundCell = Worksheets("PM2CORRELATED").Range("AB4:AB1500").FindNext
Loop
End Sub
Комментарии:
1. Должно быть
Dim FoundCell As range
Ответ №1:
Вместо того, чтобы удалять строки одну за другой, вы можете отфильтровать их и удалить результаты
Public Sub DeleteRows()
' Set target sheet
Dim targetSheet As Worksheet
Set targetSheet = ThisWorkbook.Worksheets("PM2CORRELATED")
' Set target range
Dim targetRange As Range
Set targetRange = targetSheet.Range("AA4:AA1500")
' Filter cells
targetRange.AutoFilter Field:=1, Criteria1:=1
' Delete the filtered rows
targetRange.Offset(1, 0).Resize(targetRange.Rows.Count - 1).SpecialCells(xlCellTypeVisible).EntireRow.Delete
' Turn off autofilter
targetSheet.AutoFilterMode = False
If targetSheet.FilterMode = True Then
targetSheet.ShowAllData
End If
End Sub
Комментарии:
1. И это работает как по волшебству! Большое спасибо!
2. Не забудьте отметить ответ, чтобы другие тоже могли его найти
Ответ №2:
Здесь вы совершаете типичную ошибку новичка: когда вы удаляете что-то из списка, вам нужно делать это от конца к началу, а не от начала до конца.
Позвольте мне привести вам пример: у вас есть коллекция [1,0,0,1,1,1]
, и вы хотите удалить каждый ноль, сначала вы делаете это от начала до конца:
(Pseudo-code)
For index=1 to 6
if collection[index] = 0
then collection.remove(index)
next
Это то, что происходит с вашим индексом и вашей коллекцией:
index = 1, collection = [1,0,0,1,1,1], collection[index] = 1 => do nothing
index = 2, collection = [1,0,0,1,1,1], collection[index] = 0 => remove the second entry
result after removal : collection = [1,0,1,0,1]
index = 3, collection = [1,0,1,1,1], collection[index] = 1 => do nothing
index = 4, collection = [1,0,1,1,1], collection[index] = 1 => do nothing
index = 5, collection = [1,0,1,1,1], collection[index] = 1 => do nothing
index = 6, collection = [1,0,1,0,1], collection[index] = ERROR: there are no 6 elements anymore
Видите ли, когда вы переходите от начала к концу, дубликаты приводят к тому, что некоторые записи не удаляются, и вы даже можете получить сообщение об ошибке.
Теперь давайте сделаем это наоборот:
(Again pseudo-code)
from index=6 to 1
if collection[index] = 0
then collection.remove(index)
step -1
Это то, что происходит с вашим индексом и вашей коллекцией:
index = 6, collection = [1,0,0,1,1,1], collection[index] = 1 => do nothing
index = 5, collection = [1,0,0,1,1,1], collection[index] = 1 => do nothing
index = 4, collection = [1,0,0,1,1,1], collection[index] = 1 => do nothing
index = 3, collection = [1,0,0,1,1,1], collection[index] = 0 => remove the third entry:
collection = [1,0,1,1,1]
index = 2, collection = [1,0,1,1,1], collection[index] = 0 => remove the second entry:
collection = [1,1,1,1]
index = 1, collection = [1,1,1,1], collection[index] = 1 => do nothing
Удачи