簡體   English   中英

獲取下拉列表的索引號

[英]Obtaining the Index Number of a Drop-Down List

簡而言之,我試圖通過VBA獲取下拉列表的索引號。在這種情況下,下拉列表是通過數據驗證創建的。

長話短說,我創建了一個簡單的工作表,其中包含一些通過數據驗證制作的下拉列表,其中僅包含字符串。

根據用戶的選擇,我想根據所選的選項執行一些任務。 與其將整個字符串輸入 select case 或 if-else then 語句,不如獲取該特定下拉列表中所選選項的索引號是一種更有效的方法。

我知道 function 符合我的確切要求的 ListIndex 屬性,但據我所知,它僅適用於列表框和 combobox。

我也知道另一個類似的問題: Get position (in number) of selected item in dropdown list 但是,此解決方案對我不起作用,在大多數情況下,在選項中選擇了下拉列表中的第一項以外的選項時,返回的值為“ 0”。 從我對VBA的粗淺理解來看,在各種下拉選項之間沒有重復的單詞的情況下,似乎只有function符合預期。

如果有人能詳細說明解決方案代碼,我也將不勝感激,因為我想了解到底發生了什么,並增加我對 VBA 編程的了解。

這對我來說很好——類似於 Doug 在您的鏈接帖子中的回答。

Sub tester()

    Debug.Print SelectedListIndex([F1])

End Sub



'If `c` has a list-based validation (from direct entry, not a range reference)
'  and a value has been selected, return the index of the value in the list
Function SelectedListIndex(c As Range)
    Dim arr, m, v
    m = -1
    v = c.Value
    If Len(v) > 0 Then
        If Not c.Validation Is Nothing Then
            If c.Validation.Type = xlValidateList Then
                arr = Split(c.Validation.Formula1, _
                            Application.International(xlListSeparator))
                m = Application.Match(c.Value, arr, 0)
            End If
        End If
    End If
    SelectedListIndex = IIf(IsError(m), -1, m)
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM