VBA定义每个部分的宏(字符串)的开头和结尾?

时间:2016-07-15 10:57:01

标签: excel vba excel-vba

The example of my table Excel

您好,如何根据字符串定义Interval并将其循环到其中? 例如,从1开始定义到2结束,然后移动到另一个间隔? 这是为了搜索名称" xx"例如,在每个间隔中,并使用msgbox显示单元格的地址。

我做了以下代码,问题是我不知道如何制作这段时间..有人可以帮我吗?感谢。

Sub search_for_names()

    lastligne = ThisWorkbook.Sheets("students").Cells(Rows.Count, 1).End(xlUp).Row
    For i = 1 To lastligne
        Set rnginformation = Cells(i, 1)
        Set rngaction = Cells(i, 2)
        If rnginformation = "1" And rngaction = "start" Then
            MsgBox "beginning of interval"
            For k = 1 To rnginformation = "2" And rngaction = "end"    'define the end of interval
                MsgBox "x"
                Set actionAnalyse = ThisWorkbook.Sheets("students").Cells(k, 2).Find(xx, LookIn:=xlValues)
                firstAddress = rngaction.Address
                MsgBox firstAddress
            Next k
        End If
    Next i

End Sub

1 个答案:

答案 0 :(得分:2)

当您发现起始行设置的变量等于i lStart = i时。然后,当您发现最后一行构建从起始行到i .Range(.Cells(lStart, 2), .Cells(i, 2))的范围时。由于您实际上希望lStart和i .Range(.Cells(lStart + 1, 2), .Cells(i -1, 2))之间的行更有效。

Sub search_for_names()
    Dim i As Long, lastligne As Long, lStart As Long
    Dim actionAnalyse As Range, rSearch As Range

    With Sheets("students")
        lastligne = .Cells(Rows.Count, 1).End(xlUp).Row
        For i = 1 To lastligne

            If .Cells(i, 1) = "1" And .Cells(i, 2) = "start" Then lStart = i

            If .Cells(i, 1) = "2" And .Cells(i, 2) = "end" Then

                Set rSearch = .Range(.Cells(lStart, 2), .Cells(i, 2))

                Set actionAnalyse = rSearch.Find("xx", LookIn:=xlValues)

                If Not actionAnalyse Is Nothing Then

                    MsgBox actionAnalyse.Address

                End If
            End If

        Next i

    End With
End Sub