Remove an Element from an Array
The RemoveElement function checks each element in an array for a target value. If the target value is found, that item is removed from the array.
How It Works
This function requires an array and target search value. The function loops through each element in the array and compares the value to the search string. If the values do not match, the element is added to a temporary array. If the values do match, it is skipped and thus not included in the array. After all elements are checked, the temporary array is returned with all references to the target search value removed.
Implementation
This function requires two parametersan array of values and the search value.
Function RemoveElement (varFromList As Variant, varTarget As Variant) As Variant '----------------------------------------------------------------------- ' Removes an element from an array. '----------------------------------------------------------------------- Redim ReturnArray(0) As Variant Dim i As Integer i = 0 Forall varElement In varFromList Redim Preserve ReturnArray (i) As Variant If varElement <> varTarget Then ReturnArray(i) = varElement i = i + 1 End If End Forall RemoveElement = ReturnArray End Function
The following illustrates how the function could be called from an action button. In this example, the name "Tom" is removed from the array theTeam (see Figure 13.3). After the function call, the returned array will contain "Henry", "Mark", and "Steve".
Sub Click(Source As Button) Dim newTeam As Variant Dim theTeam (0 To 3) As String theTeam (0) = "Tom" theTeam (1) = "Henry" theTeam (2) = "Mark" theTeam (3) = "Steve" Msgbox Implode ( theTeam, ", "), , "Original Team" newTeam = removeElement ( theTeam, "Tom" ) Msgbox Implode (newTeam, ", "), , "New Team" End Sub
Figure 13.3. Remove an element from an array
Compare Two Arrays
|