在动态数组中搜索值(vba)

时间:2016-07-13 18:54:51

标签: arrays excel vba excel-vba

用户通过使用复选框选择所需的选项。每个复选框的标题值存储在动态数组中,然后显示在确认选择的消息框中。

我现在需要遍历一系列单元格,在每一行确定单元格(x,4)是否等于数组中的任何值,但我不知道如何循环。请参阅下面的代码,其中填充了数组。

提前谢谢!

Sub ProcessStrats_Click()
Dim ctl As Control
Dim cnt As Long
Dim msg As String
Dim i As Long
Dim cResp As Integer
Dim stArray() As Variant

    cnt = 0                                             'Initialize counter outside of loop
    For Each ctl In StratFill.Controls                  'look at every control in StratForm box
        If Left(ctl.Name, 8) = "CheckBox" Then          'if the control is named 'checkbox' then
            If ctl.Value = True Then                    'if the control is marked as 'true' i.e. checked, then
                ReDim Preserve stArray(0 To cnt)        'Reset the array dimension on each iteration of loop
                stArray(cnt) = ctl.Caption              'Add value in value of checkbox caption to Array
                cnt = cnt + 1                           'Advance the counter to next array item
            End If
        End If
    Next

    Unload StratFill                                    'unload and close stratfill form


    msg = "The following strategies will be priced:" & vbNewLine & vbNewLine
    For i = LBound(stArray) To UBound(stArray)          'loops through all values of array
           msg = msg & stArray(i) & vbCR                'strings together displayed txt
    Next i

        If MsgBox(msg, vbYesNo, "Confirm Strategies") = vbYes Then
                                                                    'if yes is clicked
            Call RunPricing                                         '"RunPricing" will run
        Else                                                        'if no is clicked
            StratFill.Show                                          'then the strategy selector box will display again
        End If

End Sub

1 个答案:

答案 0 :(得分:0)

试试这个:

For i = 1 To UBound(stArray)                        'loops through all values of array

    Range("$D2:" & Range("D" & Rows.Count).End(xlUp).Address).Select

    Selection.Find(What:=stArray(i), After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Offset(0, 2).Select

    msg = msg & stArray(i) & ActiveCell.Value & vbCR                'strings together displayed txt
Next i