PDA

View Full Version : Worksheet object onClickEvent with changing cells issue



abdulsamad
08-15-2020, 10:52 PM
Hi I am creating a code for automating a creation of invoice but I am in problem
I wanted to make a onclick event with dynamic range but when I run the code the whole code crashes
Here is the code




Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim total As Integer
Range("A1").Select
Selection.End(xlDown).Select
total = ActiveCell.Value
If Target.Cells.CountLarge <> 1 Then Exit Sub
If Not Intersect(Target, Range("H2:H" & (total + 1))) Is Nothing Then

Application.EnableEvents = False

If Target = 1 Then
Target = 0
Else
Target = 1
End If


Application.EnableEvents = True
Range("A1").Select
End If
End Sub

SamT
08-16-2020, 10:20 AM
Range("A1").Select
Selection.End(xlDown).Select
total = ActiveCell.Value 'A1 is the active cell
If you MUST use Total, use this form
Dim total As Integer, Wsf
Set Wsf = WorksheetFunction
total = Wsf.Sum(Range(Range("A1"), Range("A1").End(xlDown)).Value)


See if this does what you want

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Intersect(Target, Range(Range("H2"), Cells(Rows.Count, "H").End(xlUp).Offset(1))) Is Nothing Then Exit Sub

Application.EnableEvents = False

If Target = 1 Then
Target = 0
Else
Target = 1
End If

Range("A1").Select 'Before EnableEvents, else it triggers the Event again

Application.EnableEvents = True
End Sub