excelvbaruntime-errorcelltype-mismatch

type mismatch in for cycle


my code get an error in the line

If .Cells(i, 1).Value = .Cells(i - 1, 1).Value Then

I don't know why, from my little experience there's nothing wrong but i keep getting this Type mismatch (Error 13), can someone help me? here's my full code

Sub tests()
'Option Explicit

'Private Sub Workbook_Open()

Dim lastrow As Integer
Dim i As Integer
Dim orig As String
Dim v As Variant
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim exApp As Excel.Application
Dim exwb As Excel.Workbook


'Application.EnableEvents = True
'On Error GoTo Exitsub

Set wbBook = Workbooks("SHELF LIFE.xlsm")
Set wsSheet = wbBook.Sheets("Shelf Life Data")

Set exApp = CreateObject("Excel.Application")
Workbooks.Open ("link.xlsm")
Set exwb = Workbooks("file name.xlsm")
    
With exwb
    lastrow = Cells(Rows.Count, "L").End(xlUp).Row
    v = .Sheets("SINCE 170522").Range(Cells(4, 12), Cells(lastrow, 12)).Value
    .Close
End With

With wsSheet
    .Range(Cells(2, 1), Cells(lastrow, 1)).Value = v
    .Range(Cells(1, 1), Cells(lastrow, 2)).Sort Key1:=Range("A1"), _
        Order1:=xlAscending, _
        Header:=xlYes
    lastrow = Cells(Rows.Count, "A").End(xlUp).Row
        For i = lastrow To 2 Step -1
            If .Cells(i, 1).Value = .Cells(i - 1, 1).Value Then
                .Rows(i).EntireRow.Delete
            Else
            End If
        Next i
End With

Exitsub:

End Sub


Solution

  • You got lastrow from a range starting on row#4, so you need to adjust that if you want to place the array starting at row#2, or your last 2 values will be #N/A because the range you're placing the array onto is larger than the array.

    Those #N/A values account for the "type mismatch" error when you start to loop over the values.

    You can do this instead:
    .Range("A2").Resize(UBound(v, 1), 1).Value = v