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

后端 未结 6 1551
夕颜
夕颜 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:01

    I was just doing some research on accessing the contents of a Shapes dropdown control, and discovered another approach to solving this problem that you might find helpful.

    Any range that can have a validation rule applied can have that rule applied programmatically. Thus, if you want to apply a rule to cell A1, you can do this:

    ActiveSheet.Range("A1").Validation.Add xlValidateList, , , "use, this, list"
    

    The above adds an in-cell dropdown validation that contains the items "use," "this," and "list." If you override the Worksheet_SelectionChange() event, and check for specific ranges within it, you can call any number of routines to create/delete validation rules. The beauty of this method is that the list referred to can be any list that can be created in VBA. I needed a dynamically-generated list of an ever-changing subset of the worksheets in a workbook, which I then concatenated together to create the validation list.

    In the Worksheet_SelectionChange() event, I check for the range and then if it matches, fire the validation rule sub, thus:

    Private Sub Worksheet_SelectionChange(ByVal Target as Range)
    
        If Target.Address = "$A$1" Then
            UpdateValidation
        End If
    
    End Sub
    

    The validation list-builder code in UpdateValidation() does this:

    Public Sub UpdateValidation()
    
        Dim sList as String
        Dim oSheet as Worksheet
    
        For Each oSheet in Worksheets
            sList = sList & oSheet.Name & ","
        Next
    
        sList = left(sList, len(sList) -1)  ' Trim off the trailing comma
    
        ActiveSheet.Range("A1").Validation.Delete
        ActiveSheet.Range("A1").Validation.Add xlValidateList, , , sList
    
    End Sub
    

    And now, when the user clicks the dropdown arrow, he/she will be presented with the updated validation list.

提交回复
热议问题