摆脱。在VBA代码中选择

时间:2017-02-10 19:09:45

标签: vba excel-vba excel

我想摆脱下面代码中的sht2.Selectsht2.Range("B2").Select。有没有办法做到这一点?

Sub Remaining()

Dim sht2 As Worksheet    
Dim cell As Range

Set sht2 = ThisWorkbook.Worksheets("Sheet2")

sht2.Select
sht2.Range("B2").Select    
With sht2
    For Each cell In .Range("B2", Cells(Rows.Count, "B").End(xlUp))
        If .Range("A:A").Find(What:=cell.Value2, LookAt:=xlWhole) Is Nothing Then
           Intersect(.UsedRange, cell.EntireRow).Offset(, 1).Copy Sheets("Sheet1").Cells(Rows.Count, "L").End(xlUp).Offset(1)
           cell.Interior.Color = vbYellow
       End If
    Next cell
End With

End Sub

1 个答案:

答案 0 :(得分:6)

Sub Remaining()

    Dim sht2 As Worksheet
    Dim cell As Range

    Set sht2 = ThisWorkbook.Worksheets("Sheet2")

    With sht2
        'A few fixes in the following line to make sure everything
        '   is referencing the correct sheet
        For Each cell In .Range(.Range("B2"), .Cells(.Rows.Count, "B").End(xlUp))
            If .Range("A:A").Find(What:=cell.Value2, LookAt:=xlWhole) Is Nothing Then
               Intersect(.UsedRange, cell.EntireRow).Offset(, 1).Copy _
                      Sheets("Sheet1").Cells(Rows.Count, "L").End(xlUp).Offset(1)
               cell.Interior.Color = vbYellow
           End If
        Next cell
    End With

End Sub