O
onedaywhen
What is the best (quickest, most efficient) way of deleting a row from
a range by matching a value in a key column? For example, my range is
A1:C10 and I want to delete the row which has the value "Pies" in the
first column, so if A4="Pies" I want to delete A4:C4 by shifting cells
A5:C10 up (I'm unconcerned about cells A11:C65536; they can also shift
up or remain where they are).
My current approach (code below) is to read the range into a variant
as an array, loop through the 'rows' in the array and if I find a
match in the key 'column' I use the Delete method on the range.
I wondered if there is a better way of doing this e.g. somehow remove
the 'row' from the array, append a blank 'row' and read the values
back to the range?
Please note that in reality I'm matching one or more columns and the
ranges are a lot larger than 10 rows! Many thanks.
Here's my existing code:
Private Function DeleteByKey(ExcelRange As Excel.Range, _
ByVal KeyColumn As Long, _
ByVal KeyValue As Variant) As Boolean
Dim vntArray As Variant
Dim lngRows As Long
Dim lngCounterRows As Long
vntArray = ExcelRange.Value
lngRows = UBound(vntArray, 1)
' Loop through rows and try to match key
For lngCounterRows = 1 To lngRows
If vntArray(lngCounterRows, KeyColumn) = KeyValue Then
' Match
ExcelRange.Rows(lngCounterRows).Delete xlShiftUp
DeleteByKey = True
Exit Function
End If
Next
' No match
DeleteByKey = False
End Function
Public Sub TestDeleteByKey()
If DeleteByKey(Range("A1:C10"), 1, "Pies") Then
MsgBox "Success"
End If
End Sub
a range by matching a value in a key column? For example, my range is
A1:C10 and I want to delete the row which has the value "Pies" in the
first column, so if A4="Pies" I want to delete A4:C4 by shifting cells
A5:C10 up (I'm unconcerned about cells A11:C65536; they can also shift
up or remain where they are).
My current approach (code below) is to read the range into a variant
as an array, loop through the 'rows' in the array and if I find a
match in the key 'column' I use the Delete method on the range.
I wondered if there is a better way of doing this e.g. somehow remove
the 'row' from the array, append a blank 'row' and read the values
back to the range?
Please note that in reality I'm matching one or more columns and the
ranges are a lot larger than 10 rows! Many thanks.
Here's my existing code:
Private Function DeleteByKey(ExcelRange As Excel.Range, _
ByVal KeyColumn As Long, _
ByVal KeyValue As Variant) As Boolean
Dim vntArray As Variant
Dim lngRows As Long
Dim lngCounterRows As Long
vntArray = ExcelRange.Value
lngRows = UBound(vntArray, 1)
' Loop through rows and try to match key
For lngCounterRows = 1 To lngRows
If vntArray(lngCounterRows, KeyColumn) = KeyValue Then
' Match
ExcelRange.Rows(lngCounterRows).Delete xlShiftUp
DeleteByKey = True
Exit Function
End If
Next
' No match
DeleteByKey = False
End Function
Public Sub TestDeleteByKey()
If DeleteByKey(Range("A1:C10"), 1, "Pies") Then
MsgBox "Success"
End If
End Sub