VBA在最后一个真实条件下退出循环

时间:2016-09-27 19:00:15

标签: vba excel-vba excel

我正在构建一个宏,该宏将浏览某个报告类型的所有xls文件的文件夹,并将它们列在包含整个路径的工作表中。然后按升序对它们进行排序,找到最新的文件,将其打开,并将其中的信息复制到空白文件中,作为聚合来自多种报告的最新数据的过程。

找到最新文件后,问题是退出循环:

Dim i As Variant
Dim myarray() As Integer
Dim myarray2() As Variant

i = 0

For Each cell In Range("C1:C" & x)
    If InStr(1, cell, "proof") Then
        i = i + 1
        Debug.Print i & " " & cell.value
        ReDim myarray(i)
        ReDim Preserve myarray2(cell)
    End If

    Do
    Loop Until InStr(1, cell, "proof")
Next cell

这是一个试用代码 - 它会查找指定文件夹中文件名中包含"proof"的所有文件,然后在即时窗口中打印它们。动态数组存储每个文件名,直到循环结束,并且Do Until循环例程应该在最后检查为true的条件下停止它 - 它将被打开并从中复制信息。问题是Do Until循环锁定整个例程,因为第一次迭代是真的会满足它,而且我不确定如何让它退出它应该的地方。 ..

Do-While循环放在同一个位置时,它最终会自行循环。

1 个答案:

答案 0 :(得分:2)

并没有真正实现你的全部目标。但你可以尝试这个开始

Option Explicit

Sub main()
    Dim i As Variant
    Dim myarray() As String
    Dim cell As Range
    Dim firstAddress As String
    Dim nFound As Long

    With Range("C1", Cells(Rows.Count, "C").End(xlUp)) '<--| reference column "C" cells from row 1 down to last non empty one
        nFound = WorksheetFunction.CountIf(.Cells, "*proof*") '<--| count occurrences of wanted substring
        If nFound = 0 Then Exit Sub '<--| exit if no occurrences
        ReDim myarray(1 To nFound) '<--| size your array to match occurrences
        Set cell = .Find(what:="proof", after:=.Cells(.Rows.Count, 1), LookIn:=xlValues, lookat:=xlPart, searchdirection:=xlNext) '<--| find first occurrence
        firstAddress = cell.Address '<--| store first occurrence address
        Do
            i = i + 1 '<-- update array index
            myarray(i) = cell.Value '<--| update array current index content
            Set cell = .FindNext(cell) '<--| search for next occurrence
        Loop While cell.Address <> firstAddress '<--| exit if occurrence wrapped back to the first one
    End With
End Sub