Can I use VBA function to return a (dynamic) list of acceptable values into Excel's data validation?

后端 未结 6 1540
夕颜
夕颜 2020-12-19 11:28

For a given cell, I select Data/Validation and set Allow to \"List\". I now wish to set Source like so:

=rNames(REGS)

but that does not work (name not found

6条回答
  •  感情败类
    2020-12-19 12:20

    @user5149293 I higly appreciate your code, but I recommend to prevent the collection from throwing an error, when adding duplicate values. The usage of a custom formula in the data validation list or in Name-Manager-Formula prevents the code from using the vbe debugger, which makes it very hard to trace back errors here (I ran into this problem myself, when using your code). I recommend to check the existence of key in the collection with a separate function:

        Function uniqueList(R_NonUnique As Range) As Variant
        'Returns unique list as Array
    
            Dim R_TempList As Range
            Dim V_Iterator As Variant
            Dim C_UniqueItems As New Collection
    
            For Each V_Iterator In R_NonUnique
               'Check if key already exists in the Collection
               If Not HasKey(C_UniqueItems, V_Iterator.Value2) Then
                  C_UniqueItems.Add Item:="'" & V_Iterator.Parent.Name & "'!" & V_Iterator.Address, Key:=CStr(V_Iterator.Value2)
               End If
            Next V_Iterator
    
            For Each V_Iterator In C_UniqueItems
                If R_TempList Is Nothing Then
                    Set R_TempList = Range(V_Iterator)
                End If
                Set R_TempList = Union(R_TempList, Range(V_Iterator))
            Next V_Iterator
    
            Set uniqueList = R_TempList
    
        End Function
    
    
        Function HasKey(coll As Collection, strKey As String) As Boolean
        'https://stackoverflow.com/questions/38007844/generic-way-to-check-if-a-key-is-in-a-collection-in-excel-vba
            Dim var As Variant
            On Error Resume Next
            var = coll(strKey)
            HasKey = (Err.Number = 0)
            Err.Clear
    
        End Function
    

提交回复
热议问题