简体   繁体   中英

Excel getting a runtime error 13: Type mismatch

Got this error:

Sub Namecheck()
Dim FirstName As Range, LastName As Range, fnamex As Range
Dim LNCount As Double
Dim lname As Variant, fname As Variant, lname2 As Variant
Dim i As Integer, p1 As Integer

i = 1

Set FirstName = ThisWorkbook.Sheets(Sheet1).Range("B2:B47175")
Set LastName = ThisWorkbook.Sheets(Sheet1).Range("C2:C47175")

For Each lname In LastName
    i = 1 + i
    LNCount = Application.WorksheetFunction.CountIf(LastName, lname)
        If LNCount > 2 Then
            p1 = 1
            fname = cell.Offset(0, -1).Value
            Set fnamex = FirstName.Find(what:=fname, Lookat:=xlWhole)
                If Not fnamex Is Nothing Then
                ActiveCell.Cells = fnamex.Address
                lname2 = cell.Offset(0, 1).Value
                    If lname2 = lname Then
                    ActiveCell.Interior.ColorIndex = 36
                    End If
                End If
        End If

Next

End Sub

Any ideas?

Non VBA solution.

use Conditional formatting :

Step1:

Select entire columns B:C (if you want to color only one column, select only it, eg select column B for highlighting only firstnames). With selected columns go to Conditional Formatting --> New Rule..

在此处输入图片说明

Step2:

Select Use a formula to detect which cells to format , enter formula =COUNTIFs($B:$B,$B1,$C:$C,$C1)>1 and choose desired format. Press OK.

在此处输入图片说明

Result:

在此处输入图片说明


VBA solution

Sub Namecheck()
    Dim lastrow As Long
    Dim rng As Range
    Dim lname As Range

    With ThisWorkbook.Sheets("Sheet1")
        lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
        Set rng = .Range("B2:C" & lastrow)
    End With
    For Each lname In rng.Columns(2).Cells
        If Application.CountIfs(rng.Columns(2), lname, rng.Columns(1), lname.Offset(, -1)) > 1 Then
            lname.Interior.ColorIndex = 36 'change color of lastname
            lname.Offset(, -1).Interior.ColorIndex = 36 'change color of firstname
        End If
    Next
End Sub

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