偏移到anthor列并在条件满足时停止

时间:2016-02-07 09:23:26

标签: excel vba excel-vba

如果我的数据集是5x5。

0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 1

我想将我的选择移到单元格是1.

我写了一个宏,但我只能要求它在单元格为1时停止。

我不知道如何在5列通过后将excel转移到另一行。

谁能告诉我怎么做?

THX。

Sub macro1()
'
Range("A2").Select
Do
ActiveCell.Offset(0, 1).Select
Loop Until ActiveCell.Value = 1
End Sub

2 个答案:

答案 0 :(得分:3)

您可以找到所需的内容,而不是遍历所有单元格。从您提供的代码看,您的数据看起来就像是A2。

Sub Find_One()
    Dim rng As Range, oC As Range, s As String
    s = 1    ' this is what you want to find
    Set rng = Range("A2:E6")

    Set oC = rng.Find(what:=s, lookat:=xlWhole)

    If Not oC Is Nothing Then
        Cells(oC.Row, oC.Column).Select
    Else: MsgBox "Not Found"
        Exit Sub
    End If

End Sub

如果" 1"将不止一次出现,那么这段代码对你有用。

Sub Select_1()
    Dim FrstRng As Range
    Dim UnionRng As Range
    Dim c As Range

    Set FrstRng = Range("A2:E6")

    For Each c In FrstRng.Cells

        If c = 1 Then
            If Not UnionRng Is Nothing Then
                Set UnionRng = Union(UnionRng, c)    'adds to the range
            Else
                Set UnionRng = c
            End If
        End If

    Next c

    UnionRng.Select

End Sub

答案 1 :(得分:2)

试试这个

Sub macro1()
For Each cell In Range("A1:E5")
    If cell.Value = 1 Then
        cell.Select
        Exit For
    End If
Next cell
End Sub