【问题标题】:Fill a two-dimensional array, split code on multiple lines填充一个二维数组,多行拆分代码
【发布时间】:2020-11-22 00:02:09
【问题描述】:

我必须用 8 x 5 = 40 个值填充一个二维数组。

以下代码有效。

Sub ReadLabelPositions()
    Dim Arr_labelpositions() As Variant   ' Array 8 rows + 5 columns
                                          ' name label, top position, left position, top position2, left position2
    Dim Int_Counter1, Int_Counter2 As Integer
      
    ' fill array
    Arr_labelpositions() = [{"lbl_N",114, 222, 104, 212; "lbl_NO", 144, 144, 134, 154; "lbl_O", 210, 252, 210, 256; "lbl_ZO", 276, 222, 276, 232 ; "lbl_Z",300, 144, 310, 144; "lbl_ZW", 276, 54, 276, 44; "lbl_W", 210, 36, 210, 26; "lbl_NW", 144, 54, 144, 44 }]
    'loop through array
    For Int_Counter1 = 1 To UBound(Arr_labelpositions, 1)
        For Int_Counter2 = 1 To UBound(Arr_labelpositions, 2)
            Debug.Print Arr_labelpositions(Int_Counter1, Int_Counter2)
        Next Int_Counter2
    Next Int_Counter1
End Sub

我想分割我将值分配给数组的行,因为该行太长了。

类似这样的:

Arr_labelpositions() = [{"lbl_N",114, 222, 104, 212; _ <br>
                        "lbl_NO", 144, 144, 134, 154; _ <br>
                        "lbl_O", 210, 252, 210, 256; _  <br> etc...

【问题讨论】:

标签: arrays excel vba multidimensional-array populate


【解决方案1】:

VBA 不支持从静态值创建多维数组。为了实现您的目标,我建议使用集合和数组的组合。 Collection 的每个 Item 都将包含一个数组。

Dim myCOlection as Collection
Set myCollection=New COllection
       
With myCollection

    .add Array("lbl_N",114, 222, 104, 212)
    .add Array("lbl_NO", 144, 144, 134, 154)
   ' etc etc.

End with

您现在可以使用语法引用每个数组中的项目

 ThisValue = myCollection(x)(y)

其中 x 是 myCollection 中的项目(实际上是 myCollection.Item(x)),Y 是数组中的索引。

您可能还想看看使用 Scripting.Dictionary 而不是 Collection 是否会给您带来任何好处。

【讨论】:

  • “VBA 不支持从静态值创建多维数组” 我相信@FaneDuru 的回答演示了如何做到这一点..
  • @RonRosenfeld FaneDuru 展示了如何设置所谓的锯齿状数组(数组数组),其中锯齿状数组中的每个项目都使用 (x)(y) 语法而不是 (x, y) 语法.. 你不能创建一个二维数组(你可以使用 Array 函数和一组文字访问项目使用 (x,y) ,如 OP 代码中所示。
【解决方案2】:

恐怕你不能(以你尝试的方式)。您可以使用数组数组,以下一种方式构建并像这样处理:

Sub testSplitArrayBis()
  Dim Arr_labelpositions() As Variant, Int_Counter1 As Long, Int_Counter2 As Long
  Arr_labelpositions() = Array(Array("lbl_N", 114, 222, 104, 212), _
                Array("lbl_NO", 144, 144, 134, 154), _
                Array("lbl_O", 210, 252, 210, 256), _
                Array("lbl_ZO", 276, 222, 276, 232), _
                Array("lbl_Z", 300, 144, 310, 144), _
                Array("lbl_ZW", 276, 54, 276, 44), _
                Array("lbl_W", 210, 36, 210, 26), _
                Array("lbl_NW", 144, 54, 144, 44))
  'loop through array
  For Int_Counter1 = 0 To UBound(Arr_labelpositions)
        For Int_Counter2 = 0 To UBound(Arr_labelpositions(Int_Counter1))
            Debug.Print Arr_labelpositions(Int_Counter1)(Int_Counter2)
        Next Int_Counter2
    Next Int_Counter1
End Sub

【讨论】:

    猜你喜欢
    • 2015-01-24
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2016-05-27
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多