Search code examples
vbaexceldynamic-arrays

VBA Filter Function for dynamic array doesn't seem to be filtering on occasion


I am writing a subroutine in VBA to cycle through all the listed job numbers in a multi-tab time sheet and create a list of all job numbers that have been used (so it takes the original list (with possibly multiple job number occurrences) and creates a list with only one occurrence of each job number. The job numbers on each sheet are found in range("A8:A30"). The code below seems to work for the first several job names on the sample that I'm testing, but then seems to stop filtering. A8:A21 of the first sheet is:

14GCI393
14GCI393
13GCI373
13GCI373

13GCI388
13GCI367:2
14GCI408
14GCI408
13GCI373
13GCI388
14GCI415
14GCI415
00GCI000

And the code is:

Sub listusedjobs()
Dim usedjobs() As String
Dim nextjob As String
Dim i, m, n, lastsheetindexnumber As Integer

Application.ScreenUpdating = False
lastsheetindexnumber = ThisWorkbook.Sheets.Count
m = 0
ReDim usedjobs(m)
usedjobs(m) = "initialize"

For i = 1 To lastsheetindexnumber
    Sheets(i).Activate
    For n = 8 To 30
        nextjob = Range("A" & n).Value
        If Not IsInArray(nextjob, usedjobs) Then                                'determine if nextjob is already in usedjobs()
            ReDim usedjobs(m)
            usedjobs(m) = nextjob                                               'Add each unique job to array "usedjobs"
            Sheets(lastsheetindexnumber).Cells(m + 40, 1).Value = nextjob       'Print job name that was just added
            m = m + 1
        End If
    Next n
Next i
Application.ScreenUpdating = True
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = (UBound(Filter(arr, stringToBeFound, , vbTextCompare)) > -1)
End Function

Any help figuring out what is going wrong will be much appreciated! The current output I get for this code is below and contains multiple doubles.

14GCI393
13GCI373
13GCI388
13GCI367:2
14GCI408
13GCI373
13GCI388
14GCI415
00GCI000

Solution

  • I think that your problem may be not using ReDim Preserve inside your If Not