2016-09-14 76 views
-1

我在工作表中有一个下拉列表。当我做出选择时,是否有可能获取列表中所选项目之前和之后的项目?VBA:下拉列表 - 获取所选项目之前和之后的项目

例子:

My List

在上面的列表 - 如果用户选择 “Kylo”,我想 “后汉书” 和 “累啊”。 如果选择“Luke”,我想获得“Leia”。 如果选择了“达斯”,我想获得“汉”。

这可能吗?

干杯, VJ

+0

我认为这是可能的。您可以使用列表框的“Row Source”属性将列表框中的所有条目作为字符串,然后您可以使用split函数从该字符串中创建一个数组,然后根据数组进行任何操作。 – Blenikos

+0

但是,上述可能是许多类似解决方案之一! – Blenikos

+0

谢谢Blenikos。就像我在下面提到的,我没有使用组合框,它实际上是一个内嵌数据验证(List)。这可以通过单元格下拉列表实现吗? –

回答

1

的问题没有足够的细节一个很好的答案,但是从我的理解,你有值的范围#DataSheet!A2:A51列表,并在细胞A1所选择的项目所以像:

Dim r As Range, c As Range 
Set r = [#DataSheet!A2:A51] 
Set c = r.Find([A1]) 
If Not c Is Nothing Then 
    If c.Row > r.Row Then MsgBox "Before: " & c(0) 
    If c.Row < r.Row + r.Rows.Count Then MsgBox "After: " & c(2) 
End If 
+0

这是完美的!我只是稍微调整了一下以适应我的需求。添加“LookAt:= xlWhole”,以便FIND查看整个单元格。非常感谢你! –

1

这将做到这一点:

' rename "Combobox1" to the name of your control below 
Private Sub ComboBox1_Change() 

    Dim idx As Long 

    With ComboBox1 
     idx = .ListIndex 
     If idx = 0 Then 
      MsgBox "Next item: " & .List(idx + 1, 0) 
     ElseIf idx = .ListCount - 1 Then 
      MsgBox "Previous item: " & .List(idx - 1, 0) 
     Else 
      MsgBox "Previous item: " & .List(idx - 1, 0) & Chr(13) & "Next item: " & .List(idx + 1, 0) 
     End If 
    End With 

End Sub 
+0

感谢Miqi180。但我没有使用组合框,它实际上是一个内嵌数据验证(List)。这可以通过单元格下拉列表实现吗? –

0

我结束了进口范围到一个数组,然后前后发现的项目。下面简单的代码。任何投入都欢迎。感谢堆!

Sub GetItemBeforeAfter() 
Dim aArray As Variant 
Dim sItem As String 
Dim iCounter As Integer 
Dim iPosition As Integer 
Dim sItemBefore As String 
Dim sItemAfter As String 
aArray = ActiveWorkbook.Sheets("#DataSheet").Range("A2:A51").Value 
sItem = "Death Star" 
    With Application 
     For iCounter = LBound(aArray, 1) To UBound(aArray, 1) 
      iPosition = .Match(sItem, .Index(aArray, 0, iCounter), 0) 
      If IsNumeric(iPosition) Then 
       Select Case iPosition 
        Case LBound(aArray, 1) 
         sItemAfter = aArray(iPosition + 1, 1) 
         MsgBox "No Before!" 
         MsgBox "After: " & sItemAfter 
        Case UBound(aArray, 1) 
         sItemBefore = aArray(iPosition - 1, 1) 
         MsgBox "Before: " & sItemBefore 
         MsgBox "No After!" 
        Case Else 
         sItemBefore = aArray(iPosition - 1, 1) 
         sItemAfter = aArray(iPosition + 1, 1) 
         MsgBox "Before: " & sItemBefore 
         MsgBox "After: " & sItemAfter 
       End Select 
      Exit For 
      Else 
       MsgBox "Item Not Found" 
      End If 
     Next 
    End With 
End Sub 
相关问题