'Worksheet_Change triggers randomly

I have this particular issue and I can't figure out why is it happening.

I have this sheet module that whenever the user inputs or pastes a number in a cell, the cell in the first column get populated with an ID number that generated within the macro.

The problem is that the event is fired, apparently, at random and I can't pinpoint the exact method to make it work reliably. Say I'm using cell I2, whenever I input number the event fires and I get the result. Same thing happens with I3. But, on I4 it doesn't happen right away, only after several tries then it run the macro.

I tried using breakpoints to see if the macro was at least reaching the point of setting the variable, but it wasn't.

Here's my code:

Private Sub AllowMacros()

    Me.Protect UserInterfaceOnly:=True

End Sub


Private Sub Worksheet_Change(ByVal Target As Range)
    
    Dim changedCells As Range
    Dim g1 As String
    Dim g2 As String
    Dim g3 As String
    Dim g4 As String
    Dim g5 As String
    Dim g6 As String
    Dim GUID As String

    On Error GoTo Err '~~ ensure EnableEvents is turned back on if an error occurs
    
    Randomize
    g1 = Hex(4294967296# * Rnd)
    g2 = Hex(65535 * Rnd)
    g3 = Hex(65535 * Rnd)
    g4 = Hex(65535 * Rnd)
    g5 = Hex(4294967296# * Rnd)
    g6 = Hex(65535 * Rnd)
    
    GUID = "gb" & g1 & "-" & g2 & "-" & g3 & "-" & g4 & "-" & g5 & "-" & g6
    
    Set changedCells = Me.Range("I:I") '~~ explicitly refer to the correct sheet

    If Target.Count > 1 Then Exit Sub '~~ do this first, to speed things up

    If Not Application.Intersect(changedCells, Target) Is Nothing Then '~~ Target is already a range4
        Application.EnableEvents = False '~~ prevent an event cascade

        '~~ original If Then Else works fine.  But can be simplified
        
        If Target.Column = 9 And Len(Target.Value) > 0 And Me.Cells(Target.Row, 1) = "" Then
            Me.Cells(Target.Row, 1) = LCase(GUID)
       End If

    End If
    
Continue:
    Application.EnableEvents = True
    Exit Sub

'~~ Fall through to EnableEvents
Err:
    Application.EnableEvents = True '~~ ensure EnableEvents is turned back on
End Sub

Any guidance on how to solve this issue is greatly appreciated. Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source