2011-12-10 144 views

回答

8

如果您正在使用列表或組合框,ListIndex似乎是你在之後。

VB幫助ListIndex屬性:返回或設置列表框或組合框中當前選定項目的索引號。讀/寫長。備註。您不能在多選列表框中使用此屬性。

如果沒有選擇任何東西,ListIndex的值是-1。如果內存服務,它是一個基於零的索引。

ListIndex無法在設計時設置,因此它未在屬性窗口中列出。

輸入代碼時,輸​​入列表框名稱,然後點編輯器顯示所有可用的屬性。向下滾動列表,記下看起來有趣的任何內容,然後查看它們。

+0

就是這樣。我知道這是一個簡單的功能,但我找不到它。謝謝你的幫助! – jroeleveld

9

如果你正在尋找一個數據驗證列表的索引,這是我會怎麼做:

將下面的代碼放在ThisWorkbook模塊中:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) 
Dim ValidationIndex As Long 
Dim rngTest As Excel.Range 

'assumes the data validation is in a cell named "rngTest" 
On Error Resume Next 
Set rngTest = Sh.Range("rngTest") 
If rngTest Is Nothing Then 
    Exit Sub 
End If 
On Error GoTo 0 

If Not Intersect(ActiveCell, Sh.Range("rngTest")) Is Nothing Then 
    ValidationIndex = GetValidationIndex 
    MsgBox ValidationIndex 
End If 
End Sub 

將這個功能在ThisWorkbook模塊,或者在任何常規模塊中:

Function GetValidationIndex() As Long 
'returns a 1-based index 
Dim rngTest As Excel.Range 
Dim varValidationString As Variant 
Dim ErrNumber As Long 
Dim i As Long 

With ActiveCell.Validation 
    If .Type = xlValidateList Then '3 
     On Error Resume Next 
     Set rngTest = ActiveCell.Parent.Range(.Formula1) 
     'I do this goofy thing with ErrNumber to keep my indenting and flow pretty 
     ErrNumber = Err.Number 
     On Error GoTo 0 
     'if the Validation is defined as a range 
     If ErrNumber = 0 Then 
      GetValidationIndex = Application.WorksheetFunction.Match(ActiveCell.Value2, rngTest, 0) 
      Exit Function 
     'if the validation is defined by comma-separated values 
     Else 
      varValidationString = Split(.Formula1, ",") 
      For i = LBound(varValidationString) To UBound(varValidationString) 
       If varValidationString(i) = ActiveCell.Value2 Then 
        GetValidationIndex = i + 1 
        Exit Function 
       End If 
      Next i 
     End If 
    End If 
End With 
End Function 
+0

+1這一次既令人厭惡又驚人! –

+0

@ Jean-FrançoisCorbett謝謝!我很確定這不是OP想要的,也不能想到實際的用途,但寫起來很有趣。 –

+0

+1我與JCF合作:) – brettdj

0

我認爲沒有必要使用函數。你可以通過僅使用匹配功能來獲得它,就像上面Doug的答案一樣。

Dim GetValidationIndex as Integer 
Dim rngTest as Range  
' Get the validation list 
With ActiveCell.Validation 
    Set rngTest = ActiveCell.Parent.Range(.Formula1) 
end with 

GetValidationIndex = Application.WorksheetFunction.Match(ActiveCell.Value2, rngTest, 0) 
相關問題