So I'm new to VBA, and I am trying to get a macro to compare cells, and output a counter in the column next to it. Here is my code:
Sub Duplicate_Count()
'Find the last used row in a Column: column A in this example
Dim LastRow As Long
Dim value1 As String
Dim value2 As String
Dim counter As Integer
counter = 1
With ActiveSheet
LastRow = .Cells(.Rows.Count, "L").End(xlUp).Row
End With
'Search down row for duplicates
Dim i As Long
For i = 1 To LastRow
'Sets value1 and value2 to be compared
value1 = Worksheets("Sheet1").Cells(i, "L").Value
value2 = Worksheets("Sheet1").Cells(i + 1, "L").Value
'If values are not diferent then counter will not increment
If value1 <> value2 Then
counter = counter + 1
End If
'Sets the n colom to count, duplicates should not increment the counter
Sheet1.Cells(i, "N") = counter
Next i
End Sub
Okay so this code runs, and it looks it works, column "N" starts to populate, but the program freezes up, and I do not know if it is just because the file is so large that it takes a lot of time, or if something is wrong. If i restart the program i get run-time error '-2147417848 (80010108)': Method '_Default" of object "Range" failed. Any idea what that means?
Any help would be greatly appreciated, hopefully, I'm not just making dumb mistakes.
EDIT: Sub Duplicate_Count() 'Find the last used row in a Column: column A in this example
Dim LastRow As Long
Dim value1 As String
Dim value2 As String
Dim counter As Long
counter = 0
Dim sht As Worksheet
Set sht = Worksheets("Sheet1")
With ActiveSheet
LastRow = .Cells(.Rows.Count, "L").End(xlUp).Row
End With
'Search down row for duplicates
Dim i As Long
For i = 1 To LastRow
'Sets value1 and value2 to be compared
value1 = Worksheets("Sheet1").Cells(i, "L").Value
value2 = Worksheets("Sheet1").Cells(i + 1, "L").Value
'If values are not diferent then counter will not increment
If value1 <> value2 Then
counter = counter + 1
End If
'Sets the n colom to count, duplicates should not increment the counter
sht.Cells(i, "N") = counter
Next i
End Sub
This code crashes every time, and will occasionally give me an error of run-time error '-2147417848 (80010108)': Method '_Default" of object "Range" failed. I have no idea how to fix that... or what it even means.
Dimeach variable every time you loop - Dexloft