do while loop based on a value available in cell (find) in vba

耗尽温柔 提交于 2019-12-07 22:14:55

问题


Hi i am writing a code in vb to check a particular value in a sheet, if the value is not available then it should go back to another sheet to take new value to find, if the value is found i have to do some operation on that sheet i have the below code to find the value in the sheet but if i pass the same in a DO WHILE loop as condition it gives a compile error

find vaue code

Selection.Find(What:=last_received, After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate

could some one please help me to write a code of DO WHILE with the above find in the loop condition so that if the condition gives false (i,e if the value is not found in the sheet) then i should use some other value to find

this is the code that i am going to put in loop

Sheets("Extract -prev").Select
    Application.CutCopyMode = False

    ActiveWorkbook.Worksheets("Extract -prev").Sort.SortFields.Clear   'sorting with tickets
    ActiveWorkbook.Worksheets("Extract -prev").Sort.SortFields.Add Key:=Range( _
        "C2:C2147"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    With ActiveWorkbook.Worksheets("Extract -prev").Sort
        .SetRange Range("A1:AB2147")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

Application.Goto Reference:="R1C3"        'taking last received ticket
    Selection.End(xlDown).Select
    Selection.Copy
    Sheets("Calc").Select
    Application.Goto Reference:="Yesterday_last_received"
    ActiveSheet.Paste

this code takes the last ticket but based on it's availablity in next sheet "extract" i have to take one ticket previous to the last one (and on).


回答1:


Try below code :

Sub test()

    Dim lastRow As Long
    Dim rng As Range
    Dim firstCell As String

    lastRow = Sheets("sheet1").Range("A" & Rows.Count).End(xlUp).Row

    For i = 1 To lastRow
        Set rng = Sheets("sheet2").Range("A:A").Find(What:=Cells(i, 1), LookIn:=xlValues, lookAt:=xlPart, SearchOrder:=xlByRows)

        If Not rng Is Nothing Then firstCell = rng.Address

        Do While Not rng Is Nothing

            rng.Offset(0, 1) = "found"

            Set rng = Sheets("sheet2").Range("A:A").FindNext(rng)


            If Not rng Is Nothing Then
                If rng.Address = firstCell Then Exit Do
            End If

        Loop
    Next

End Sub



来源:https://stackoverflow.com/questions/16643981/do-while-loop-based-on-a-value-available-in-cell-find-in-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!