【问题标题】:VBA:: Exiting loopsVBA:: 退出循环
【发布时间】:2011-06-27 09:38:50
【问题描述】:

我正在创建一个搜索函数,它遍历一维数组以查找用户指定的答案,而我目前的问题是我只希望搜索在搜索范围内循环一次。但是,它目前卡在循环中。在搜索一次函数后如何退出此循环有什么建议吗?我目前有以下代码。我将单元格地址存储在 Results1() 数组中,我只希望每个找到的术语存储一次

P1B1 是一个单选按钮,指定函数在数据范围内搜索小于指定 (Textbox1) 值的任何值。 FindRange1 是我希望函数搜索的数据值范围。

Dim Results1() As Variant
Dim Find1 As Range
Dim FindRange1 As Range
Dim TextBox1 As Long
Dim i1 As Long

            Set FindRange1 = Worksheets("Properties").Range("P7:P1000")
            If ILsearch.P1B1.Value = True Then
                For i1 = 0 To Max
                    For Each Find1 In FindRange1
                        If (Find1.Value < TextBox1) And (Find1.Value > 0) Then
                            i1 = i1 + 1
                            ReDim Preserve Results1(i1)
                            Results1(i1) = Find1.Address
                        End If
                    Next Find1
                Next i1
            End If

【问题讨论】:

    标签: vba for-loop


    【解决方案1】:

    只需摆脱 For i1=0 to Max 循环 - 根据您的要求判断它是不需要的,因为您似乎只想访问 FindRange1 中的每个元素一次。

    【讨论】:

    • 一个解决方案是使用 Option Base 1
    【解决方案2】:

    我认为这只是循环遍历范围的问题,而不是循环遍历数组。请注意,修改循环变量(代码中的i1)通常不是明智之举。

    Dim Results1() As Variant
    Dim Find1 As Range
    Dim FindRange1 As Range
    Dim TextBox1 As Long
    Dim i1 As Long
    
        Set FindRange1 = Worksheets("Properties").Range("P7:P1000")
        If ILsearch.P1B1.Value = True Then
            i1 = 0
            For Each Find1 In FindRange1
                If (Find1.Value < TextBox1) And (Find1.Value > 0) Then
                    i1 = i1 + 1                      ' increase results upper bound by 1
                    ReDim Preserve Results1(1 to i1) ' extend array 
                    Results1(i1) = Find1.Address     ' store the new found value
                End If
            Next
        End If
    

    【讨论】:

      猜你喜欢
      • 2012-03-13
      • 1970-01-01
      • 2017-02-27
      • 2010-11-19
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      相关资源
      最近更新 更多