选择变量(在一个范围内)时,循环中的.find方法不起作用

时间:2016-09-21 13:30:08

标签: vba excel-vba find excel

我试图在一个范围内的每个单元格中循环(IN ACTIVE TAB“导入数据”)并将其与de-actvie Tab中的范围值(“BU Names”)匹配,如果单元格中包含一个不符合我选择范围的字符串我想告知用户错误

什么时候工作? 而不是一个范围内的少数单元格,我只有一个。

错误时间: 范围更明亮。

工作部分

With Worksheets("BU Names")

    LastBU = .Cells(Rows.Count, 1).End(xlUp).Row
    Worksheets("BU Names").Activate
    .Range(.Cells(2, 1), .Cells(LastBU, 1)).Select
    Worksheets("Import Data").Activate

End With

请帮助

Myrange = Range("E5:G6")

For Each cel In Myrange       
    Set cel_checker = Selection.Find(What:=cel, After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=True, SearchFormat:=False)        

    If cel_checker Is Nothing Then
        MsgBox "Please correct " & cel2 & " as this is not valid Business Unit"
    End If

Next

问题似乎是“Set cel_checker = Selection.Find”,当它保持在cel_cheker'nothing'而不是正确的值时

1 个答案:

答案 0 :(得分:0)

这应该做你想要的:

Set Myrange = Worksheets("Import Data").Range("E5:G6") '<<<< need Set here

Myrange.Parent.Activate

For Each cel In Myrange

    Is IsError(Application.Match(cel.Value, _
               Worksheets("BU Names").Range("A:A"), 0)) Then

          MsgBox "Please correct " & cel.Address & " ('" & cel.Value & _
                 "') as this is not valid Business Unit"
    End If

Next