Excel VBA嵌套数组,根据节选择提供用户名选择

时间:2017-11-02 16:37:37

标签: arrays excel vba validation

我正在尝试(最终)根据第一个(或主要)数据验证框中的用户选择,使用特定选项填充数据验证。目前我需要整理这个嵌套数组,因为我相信它将是解决这个问题的第一步。但是,我不能让这个嵌套数组填充。提前谢谢!

Sub Test_NestedArray()

Dim ws as Worksheet
Set ws = Worksheet("EOS Report")

Dim Array_Machine_List_Choices As Variant

Dim Array_Fab
Dim Array_Paint
Dim Array_Sub
Dim Array_Asy
Dim Array_Facilities

Array_Fab = Array(Range(MACHINESFAB)) 'referencing named ranges on the sheet
Array_Paint = Array(RANGE(MACHINESPAINT))
Array_Sub = Array(RANGE(MACHINESSUB))
Array_Asy = Array(RANGE(MACHINESASY))
Array_Facilities = Array(RANGE(MACHINESFACILITIES)

Array_Machine_List_Choices = Array(Array_Fab, Array_Paint, Array_Sub, Array_Asy, Array_Facilities)

MsgBox (Array_Machine_List_Choices(1)) 'see the array choices for Paint

End Sub

1 个答案:

答案 0 :(得分:1)

取消/评论。希望虽然这显示了你需要更多的评论

Sub Test_NestedArray()
    Dim ws As Worksheet
    Dim Array_Fab As Variant, Array_Paint As Variant, Array_Sub As Variant
    Dim Array_Asy As Variant, Array_Facilities As Variant, Array_Machine_List_Choices As Variant

    Set ws = Worksheets("EOS Report")
    ' Assuming all your ranges are in this worksheet. If not delete the With and the End With and the .'s in front of Range
    With ws
'        ' If data is in a single row with multiple columns
'        Array_Fab = Application.Transpose(Application.Transpose(Range("MACHINESFAB"))) 'referencing named ranges on the sheet
'        Array_Paint = Application.Transpose(Application.Transpose(Range("MACHINESPAINT")))
'        Array_Sub = Application.Transpose(Application.Transpose(Range("MACHINESSUB")))
'        Array_Asy = Application.Transpose(Application.Transpose(Range("MACHINESASY")))
'        Array_Facilities = Application.Transpose(Application.Transpose(Range("MACHINESFACILITIES")))
        ' If data is in a single column with multiple rows
        Array_Fab = Application.Transpose(Range("MACHINESFAB")) 'referencing named ranges on the sheet
        Array_Paint = Application.Transpose(Range("MACHINESPAINT"))
        Array_Sub = Application.Transpose(Range("MACHINESSUB"))
        Array_Asy = Application.Transpose(Range("MACHINESASY"))
        Array_Facilities = Application.Transpose(Range("MACHINESFACILITIES"))
    End With

    Array_Machine_List_Choices = Array(Array_Fab, Array_Paint, Array_Sub, Array_Asy, Array_Facilities)

    MsgBox Join(Array_Machine_List_Choices(1), vbNewLine) 'see the array choices for Paint
End Sub

Application.Transpose是将Range转换为1D数组的一种方法。如果将数组设置为排列,则会创建一个2D数组(即使您只是指一列)所以使用以下示例

+----+
| A1 |
+----+
| A2 |
+----+
| A3 |
+----+
| A4 |
+----+

要访问元素A1,您必须将其引用为Array(1,1)(而不是Array(0,0),因为设置数组的范围使用Base 1

通过使用Application.Tranpose技巧Excel可以创建一维数组,因此您可以将其称为Array(1)。这首先使得引用更简单,其次(更重要的是)允许您使用许多不能在2D数组上工作的数组函数,例如JoinFilter(Excel不会具有2D阵列的任何内置函数)