我的工作表中有一个下拉列表。当我做出选择时,是否可以获取列表中所选项目之前和之后的项目?
示例:
在上面的清单中 - 如果用户选择" Kylo",我想得到" Han"和"莱娅"。 如果"卢克"被选中,我想得到" Leia"。 如果" Darth"被选中,我想得到" Han"。
这可能吗?
干杯, VJ
答案 0 :(得分: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
答案 1 :(得分:1)
问题没有足够详细的答案,但据我所知,你有#DataSheet!A2:A51
范围内的值列表和单元格A1
中的选定项目,所以类似:< / p>
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
答案 2 :(得分: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