【问题标题】:Multilist selecting the first selected value and storing多列表选择第一个选定的值并存储
【发布时间】:2020-07-09 15:01:53
【问题描述】:

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

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

【问题讨论】:

  • 你的两个 if 语句还没有关闭,你能把它们添加到正确的地方
  • 那个Else/If需要和ElseIf在同一行

标签: excel vba ms-access


【解决方案1】:

正如 cmets 中所指出的,您的代码的问题之一是您最里面的 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

【讨论】:

    【解决方案2】:

    使用变体数组。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-21
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 2016-05-21
      • 1970-01-01
      相关资源
      最近更新 更多