Excel获取运行时错误13:键入不匹配

时间:2014-03-25 08:22:13

标签: excel vba excel-vba

出现此错误:

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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

非VBA解决方案。

使用Conditional formatting

<强>步骤1:

选择整个列B:C(如果您只想为一列着色,请仅选择它,例如选择列B以仅突出显示第一个列)。使用选定的列转到条件格式 - &gt;新规则..

enter image description here

<强>步骤2:

选择使用公式检测要格式化的单元格,输入公式=COUNTIFs($B:$B,$B1,$C:$C,$C1)>1并选择所需的格式。按OK。

enter image description here

<强>结果:

enter image description here


VBA解决方案

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