多列表选择第一个选择的值并存储

时间:2018-11-09 20:00:55

标签: excel vba excel-vba ms-access access-vba

我的用户表单上有一个多列表,用户可以选择多达三个项目。我想捕获第一个选定的项目并将其存储到变量病理结果中,以显示在下一个表单中。如何存储列表中的第一个选定值?这是我比较值的东西

If Me.OptCompare.Value = True Then 'storing value if the chooses to compare
    isFirst = False
        For i = 0 To Me.lstDiagnosis.ListCount - 1
            If isFirst = False Then
                If Me.lstDiagnosis.Selected(i) Then 
                   comp =  Me.lstDiagnosis.List(i, 0): isFirst = True       
                Else
                If Me.lstDiagnosis.Selected(i) Then  
                   comp = comp & " vs. " & Me.lstDiagnosis.List(i, 0) 
                End If
           End If
        Next
        Result = comp
        PathologyResults = "The pathology is the first selected, " & "."
End If

2 个答案:

答案 0 :(得分:0)

正如注释中指出的那样,代码的问题之一是,您最里面的If语句应该写为:

If Me.lstDiagnosis.Selected(i) Then 
   comp =  Me.lstDiagnosis.List(i, 0): isFirst = True
Else
    If Me.lstDiagnosis.Selected(i) Then  
       comp = comp & " vs. " & Me.lstDiagnosis.List(i, 0) 
    End If
End If

或使用ElseIf

If Me.lstDiagnosis.Selected(i) Then 
   comp =  Me.lstDiagnosis.List(i, 0): isFirst = True
ElseIf Me.lstDiagnosis.Selected(i) Then  
   comp = comp & " vs. " & Me.lstDiagnosis.List(i, 0) 
End If

但是,我个人建议使用ItemsSelected属性,以便您只需要遍历用户选择的项目而不是整个数据集:

Dim var As Variant
Dim rtn As String

If OptCompare Then
    For Each var In lstDiagnosis.ItemsSelected
        rtn = rtn & " vs. " & lstDiagnosis.ItemData(var)
    Next var
    If rtn <> "" Then rtn = Mid(rtn, 6)
End If

答案 1 :(得分:0)

使用变量数组。

Dim vR(), n As Integer
If Me.OptCompare.Value = True Then 'storing value if the chooses to compare
    For i = 0 To Me.lstDiagnosis.ListCount - 1
        If Me.lstDiagnosis.Selected(i) Then
            n = n + 1
            ReDim Preserve vR(1 To n)
            vR(n) = Me.lstDiagnosis.List(i, 0)
        End If
    Next
    Result = Join(vR, " vs.")
    PathologyResults = vR(1) & "."
End If