在下拉列表中,我有几个项目。我可以在选择项目时将该项目的位置作为数字获取吗?
答案 0 :(得分: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
答案 1 :(得分:8)
如果您使用的是列表或组合框,ListIndex
似乎就是您所追求的。
ListIndex
属性的VB帮助:返回或设置列表框或组合框中当前所选项的索引号。读/写Long。备注。您不能将此属性与多选列表框一起使用。
如果未选择任何内容,则ListIndex
的值为-1
。如果内存服务,它是一个基于零的索引。
ListIndex
无法在设计时设置,因此未在属性窗口中列出。
输入代码时,键入列表框名称,然后点击,编辑器将显示所有可用属性。向下滚动列表,记下任何看起来有趣的内容,然后查找它们。
答案 2 :(得分: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)
答案 3 :(得分:0)
函数GetValidationIndex
很好。
但是,对于某些区域设置,行 varValidationString = Split(.Formula1, ",")
无效,因为用于分隔不同值的字符是 ";"
我建议使用:
varValidationString = Split(.Formula1, Application.International(xlListSeparator))