Reputation: 13
I'm currently creating a worksheets which moves rows in Excel that contain a cell containing the text "Voltooid" to a second worksheet. I want to either move the rows, or copy+paste and delete them, based on cell value.
Up until now, I've been able to build a function that deletes rows in the table. Please see the code below:
Sub DeleteCompleted()
Dim Test1 As ListObject
Dim Test2 As Variant
Dim Rowcount As Integer
Set Test1 = Sheets("To Do Lijst").ListObjects("Table2")
Test2 = Test1.ListRows.Count
For Rowcount = 1 To Test2 Step 1
If Test1.DataBodyRange(Rowcount, 4) = "Voltooid" Then
Test1.DataBodyRange(Rowcount, 4).Delete Shift:=xlUp
Rowcount = 0
End If
Next Rowcount
Can you suggest a better format for me?
Kind regards,
Pim
Upvotes: 1
Views: 161
Reputation: 57683
Long
for row counting variables, Excel has more rows than Integer
can handle. Also never use Variant
unless you really have to.Range().Cut
and define a destination, eg next free row in another worksheet.So you end up with something like …
Sub DeleteCompleted()
Dim ToDoList As ListObject
Dim ListRowCount As Long
Dim iRow As Long
Set ToDoList = Sheets("To Do Lijst").ListObjects("Table2")
ListRowCount = ToDoList.ListRows.Count
Dim NextFreeRow As Range
For iRow = ListRowCount To 1 Step -1
With ToDoList
If .DataBodyRange(iRow, 4).Value = "Voltooid" Then
Set NextFreeRow = Worksheets("Destination").Cells(Rows.Count, 4).End(xlUp).Offset(1, -3)
ToDoList.ListRows(iRow).Range.Copy Destination:=NextFreeRow
ToDoList.ListRows(iRow).Range.Delete Shift:=xlUp
End If
End With
Next iRow
End Sub
Upvotes: 1