简体   繁体   中英

VBA Excel Error 13 Type mismatch

I have the next code that validate ID into 2 worksheets, it works okay but every time I run the macro I get the Mismatch error and I do not know what I am doing wrong or I do not know if I am missing something, I have checked all the answers before to come here but still nothing.

The error occurs at Set j = .Range("A:A").find(findValue)

This is my code:

Sub Save_comments()
Dim i As Integer
Dim j As Range

k = Sheets("List").Cells(Rows.Count, "P").End(xlUp).Row
For i = 1 To k
    findValue = Sheets("List").Cells(i, 16).Value
    With Sheets("Historical_Data")
        l = .Cells(Rows.Count, "A").End(xlUp).Row + 1
        Set j = .Range("A:A").find(findValue) '<-- error here
        If Not j Is Nothing Then
            If Sheets("List").Cells(i, 18).Value <> "" Then
                .Cells(j.Row, j.Column).Offset(0, 2).Value = Sheets("List").Cells(i, 18).Value
            End If
        Else
            .Cells(l, 1).Value = Sheets("List").Cells(i, 16).Value
            .Cells(l, 3).Value = Sheets("List").Cells(i, 18).Value
        End If
    End With
Next i
End Sub

Try to modify your code as follows:

Sub Save_comments()
Dim i As Integer
Dim j As Range

k = Sheets("List").Cells(Rows.Count, "P").End(xlUp).Row
For i = 1 To k
    findValue = Sheets("List").Cells(i, 16).Value

    If Application.IsNA(findValue) = False Then

        With Sheets("Historical_Data")
            l = .Cells(Rows.Count, "A").End(xlUp).Row + 1
            Set j = .Range("A:A").Find(findValue) '<-- error here
            If Not j Is Nothing Then
                If Sheets("List").Cells(i, 18).Value <> "" Then
                    .Cells(j.Row, j.Column).Offset(0, 2).Value = Sheets("List").Cells(i, 18).Value
                End If
            Else
                .Cells(l, 1).Value = Sheets("List").Cells(i, 16).Value
                .Cells(l, 3).Value = Sheets("List").Cells(i, 18).Value
            End If
        End With

    End If
Next i
End Sub

The reason of your error is most probably N/A value assigned to findValue variable - this means that findValue variable has some error value. Here is the list of potential error numbers:

在此处输入图片说明

This is how a minimal version of your code looks like:

Sub SaveComments()

    Dim i           As Long
    Dim j           As Range
    Dim findValue   As String

    For i = 1 To 20
        findValue = Sheets("List").Cells(i, 16).Value
        With Sheets("Historical_Data")
            Set j = .Range("A:A").Find(findValue)    '<-- error here
            Debug.Print j.Address
        End With
    Next i    
End Sub

If it does not work, simply try to see what is the findValue in the case when it breaks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM