Passing a Collection to a Change Subroutine
17:52 30 Sep 2024

I am having trouble passing a collection generated when I open a userform to a textbox change subroutine. Basically I want to use a collection to check a value that is input into the text box when data is entered into it. The problem I am having is that the change subroutine does not seem to accept the ByRef coll as Collection in the subroutine. I feel like I am missing something here as to why it won't take the collection into the subroutine. Maybe I need another way to use the collection in this specific subroutine?

Sub Barcode_Scan_Change(ByRef Part_Numbers As Collection)
'When data scanned into the "Barcode Scan" text box, the data for that part will load into the "Part Information" frame
    
    'Check for the entry to be included in the part numbers to load data into the Part Information frame
    For n = 1 To Part_Numbers.Count   
        
        If Barcode_Scan.Value = "" Then
        
            MsgBox Part_Numbers(n)
            
            Exit Sub
        
        ElseIf Part_Numbers.Item(n) = Barcode_Scan.Value Then
            
            MsgBox Part_Numbers(n)
            MsgBox "Found it!"
            
            Exit Sub    
        Else
            
            MsgBox "Part number was not found in the parts list. Please rescan and/or check part packaging for correct part number or barcode.", _
                vbOKOnly, "Incorrect Scan"
                
            Exit Sub    
        End If        
    Next n        
End Sub


Sub UserForm_Initialize()
'Code for loading the data into the form when it is opened
    
    Dim Part_Numbers As Collection
    Dim i As Integer
    Dim n As Integer
    
    'Counts cells to account for any changes with part numbers in the worksheet and sets the cell number
    n = Sheet1.Range("A" & Rows.Count).End(xlUp).Row
    
    'Enters the data into the collection for use when checking that the part number is in the list
    For i = 2 To n
        Part_Numbers.Add Sheets("Parts Status").Cells(i, 1).Value
    Next i

The top portion is the change subroutine and the lower portion is what I am doing when the form initializes. I was hoping I could just generate the collection when the form opens instead of everytime the text box changes. Maybe that would be easier? Ignore the message boxes and Exit Subs as I was just using these to test the code but I am stuck now trying to pass this collection along.

excel vba variables collections