在find方法上发生类型不匹配错误

时间:2017-03-24 09:27:31

标签: excel vba excel-vba

我试图通过比较2张纸来找到值,然后将该行复制到另一张纸上。有什么建议吗?

Sub SpecialCopy()

    Dim i As Long
    Dim cellval, rng As Range
    Dim ws1, ws2 As Worksheet
    Dim targetSh As Worksheet

    Set targetSh = ThisWorkbook.Worksheets("Sheet3")
    Set ws2 = Sheets("Sheet2")
    Set ws1 = Sheets("sheet1")
    ws2.Select

    With ActiveSheet  
        Set rng = .Range("A1:A" & .Cells(.Rows.Count, 1).End(xlUp).Row)
    End With



    For i = 2 To rng.Rows.Count

       Set cellval = ws1.Columns(1).Find(What:=ws2.Range("U" & i).Value, After:=ActiveCell, LookIn:=xlFormulas, _
            LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)

        If cellval Is Nothing Then

        Else  
            Range(Cells(1, i), Cells(33, i)).Copy Destination:=targetSh.Range("A" & targetSh.Cells(Rows.Count, "A").End(xlUp).Row + 1)

        End If

    Next i
End Sub

1 个答案:

答案 0 :(得分:1)

感觉这是对上面其他人的评论的支持,但没有人提交答案,所以这是我的准备。使用工作表变量是有意义的,因为你已经定义了它们而不是ActiveSheet,并确保你在任何地方都遵循这一点。

Sub SpecialCopy()

Dim i As Long
Dim cellval As Range, rng As Range
Dim ws1 As Worksheet, ws2 As Worksheet
Dim targetSh As Worksheet

Set targetSh = ThisWorkbook.Worksheets("Sheet3")
Set ws2 = Sheets("Sheet2")
Set ws1 = Sheets("Sheet1")

With ws2
    Set rng = .Range("A1:A" & .Cells(.Rows.Count, 1).End(xlUp).Row)
End With

For i = 2 To rng.Rows.Count
    Set cellval = ws1.Columns(1).Find(What:=ws2.Range("U" & i).Value, LookIn:=xlFormulas, _
        LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
    If Not cellval Is Nothing Then
        ws2.Range(ws2.Cells(1, i), ws2.Cells(33, i)).Copy Destination:=targetSh.Range("A" & targetSh.Cells(targetSh.Rows.Count, "A").End(xlUp).Row + 1)
    End If

Next i

End Sub