2

嗨,我正在用 vb 编写代码来检查工作表中的特定值,如果该值不可用,那么它应该返回另一个工作表以获取新值来查找,如果找到该值我必须对它进行一些操作该表我有下面的代码来查找表中的值,但是如果我在 DO WHILE 循环中传递相同的值作为条件,它会给出编译错误

查找价值代码

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

有人可以帮我写一个 DO WHILE 的代码,上面在循环条件中查找,这样如果条件为假(即,如果在工作表中找不到该值),那么我应该使用其他值来寻找

这是我要放入循环的代码

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

此代码采用最后一张票,但基于它在下一张“提取”表中的可用性,我必须在最后一张票之前(并继续)取一张票。

4

1 回答 1

3

试试下面的代码:

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

在此处输入图像描述

于 2013-05-20T07:14:49.903 回答