dimanche 16 août 2020

VBA Loop Ignoring If Statement

I'm trying to update cells based on values in a listbox, looking for the ID number in column F - I have a search bar which looks for a reference number in column C and then populates UserForm1.ListBox1, with the ID number ending up in ListBox1.List(x, 8). Also, the ID number is generated by a simple formula in order to easily give each row a unique ID: =ROW($F2). I have a very variable spreadsheet, with which we keep appointments for certain activities for work. This is a shared document and I'm trying to create means of reducing user error through automation.

My issue is that my loop doesn't work, it just starts from the top of the range and seems to ignore my IF statement. I have a multi-select listbox, which should update all the selected entries based on whether searching column F finds a matching ID number. Apologies for the crude code, as I'm a beginner and self-taught, piecing together what I can from forums like this one.

Any help would be greatly appreciated.

What I have so far (I know need to amend the range from F2-F500 to F2-lastrow, but I'm not sure if this should be the reason that the loop doesn't work at present):

    Private Sub CommandButton5_Click()
For x = 0 To ListBox1.ListCount - 1
        If ListBox1.Selected(x) = True Then
            Dim myCll As Range
            Dim myRnge As Range
            Set myRnge = Worksheets("Switch Out Tracker").Range(("F2"), ("F500"))
            For Each myCll In myRnge
                If myCll.Text = ListBox1.List(x, 8) Then
                    If myCll.Offset(0, -5).Value <> ListBox1.List(x, 0) Then
                        myCll.Offset(0, -5).Value = ListBox1.List(x, 0)
                    End If
                    If myCll.Offset(0, -3).Value <> ListBox1.List(x, 1) Then
                        myCll.Offset(0, -3).Value = ListBox1.List(x, 1)
                    End If
                    If myCll.Offset(0, -2) <> ListBox1.List(x, 2) Then
                        myCll.Offset(0, -2) = ListBox1.List(x, 2)
                    End If
                    If myCll.Offset(0, -1) <> ListBox1.List(x, 3) Then
                        myCll.Offset(0, -1) = ListBox1.List(x, 3)
                    End If
                    If myCll.Offset(0, 2) <> ListBox1.List(x, 5) Then
                        myCll.Offset(0, 2) = ListBox1.List(x, 5)
                    End If
                    If myCll.Offset(0, 3) <> ListBox1.List(x, 6) Then
                        myCll.Offset(0, 3) = ListBox1.List(x, 6)
                    End If
                End If
            Next myCll
        End If
Next x
Unload Me
Call SortsSwitchOutTracker
End Sub

Aucun commentaire:

Enregistrer un commentaire