Excel VBA - Arrays for Data Validation Reference

后端 未结 2 525
失恋的感觉
失恋的感觉 2021-01-26 14:14

I have the following code:

Sub TEST_____________Data_Validation_Machine()

Application.ScreenUpdating = False

Dim ws As Worksheet
Dim ws2 As Worksheet
Dim Range         


        
相关标签:
2条回答
  • 2021-01-26 14:22

    Not sure if this helps. Variant data type cannot hold objects, so you cannot access the range through an array.

    Sub TEST_____________Data_Validation_Machine()
    
        Application.ScreenUpdating = False
    
        Dim ws As Worksheet
        Dim ws2 As Worksheet
        Dim Range1 As Range, Range2 As Range
        Dim c As Range
        Dim Array_Machine_List_Choices As Variant
    
        Set ws = ThisWorkbook.Worksheets("EOS Report")
        Set ws2 = ThisWorkbook.Worksheets("MachineList")
        Set ws3 = ThisWorkbook.Worksheets("PlantAreaList")
    
        'Array of range names
        Array_Machine_List_Choices = Array("MACHINESFAB", "MACHINESPAINT", "MACHINESSUB", "MACHINESASY", "MACHINESFACILITIES")
    
        With ws3
            'creating an array based on the named range on the sheet "PlantAreaList"
            Array_Plant_Area_Choices = Application.Transpose(.Range("PlantAreaListCells"))
        End With
    
        'Cell below "MACHINE" based on the activecell selection of the "Plant Area" combobox:
        Set Range1 = ActiveCell.Offset(0, 1)
    
        'Cell below "PLANT AREA", based on the user selection of the combobox:
        Set Range3 = ActiveCell
    
        For i = 0 To UBound(Array_Plant_Area_Choices)
    
            If Range3 = Array_Plant_Area_Choices(i) Then
    
                If c.Interior.Pattern = xlNone Then
                    With c.Validation
                        .Delete
                        .Add Type:=xlValidateList, _
                            Formula1:="='" & ws2.Name & "'!" & Array_Machine_List_Choices(i)
                        .IgnoreBlank = True
                        .InCellDropdown = True
                    End With
                End If
            End If
        Next i
    
        Application.ScreenUpdating = True
    End Sub
    
    0 讨论(0)
  • 2021-01-26 14:42

    Is there any reason you're using VBA to accomplish this?

    There's plenty of examples on Google showing how to accomplish this with named ranges, and an example I wrote up some time back that shows how you can use a Table to host your lists that allows cascading DV many levels deep, at the following links:

    • https://chandoo.org/wp/2014/02/13/dynamic-cascading-dropdowns-that-reset/ (using VBA to reset 'downstream" DV if upstream DV later changes)
    • https://chandoo.org/wp/2014/02/25/robust-dynamic-cascading-dropdowns-without-vba/ (using formulas to stop users changing upstream DV unless downstream DV changed).
    0 讨论(0)
提交回复
热议问题