代码之家  ›  专栏  ›  技术社区  ›  surendra

从调用函数返回数组并分配给数组

vba
  •  1
  • surendra  · 技术社区  · 6 年前
    Public Sub DoSomeThing()
        Dim dict As Object
        Dim arr2(5)
        Set arr2() = aaa()
    
       For m = LBound(arr2) To UBound(arr2)
            Set dict = aaa()(m)
            Dim key As Variant
           For Each key In dict.Keys
               Debug.Print dict(key)
           Next key
      Next
    End Sub
    
    Public Function aaa() As Variant
        Dim arr(5)
       Dim dict_123 As Object
       For k = 1 To 2
           If k = 1 Then
               val1 = 300
               val2 = 500
           ElseIf k = 2 Then
               val1 = 600
               val2 = 1200
          End If
           Set dict_123 = CreateObject("Scripting.Dictionary")
           dict_123.Add "first", val1
           dict_123.Add "Second", val2
           Set arr(k) = dict_123
       Next
      aaa = arr
    End Function
    

    在这里我想从返回数组 aaa DoSomething 并从中处理该数组 DoSomeThing .我该怎么做?

    我收到无法分配给数组的错误

    1 回复  |  直到 6 年前
        1
  •  2
  •   QHarr    6 年前

    有很多错误,我不确定你到底想实现什么。您的代码在下面的“固定”上方。

    笔记:

    1. arr2 = aaa 将一个数组设置为另一个数组(不将set关键字设置为not object)。不标注尺寸 arr2 第一。
    2. 测试当前阵列( 2号跑道 )项是在尝试设置之前的字典。您只在基于0的数组中的索引1和2处添加了字典。不那么健壮 If m = 1 Or m = 2
    3. 使用 Option Explicit 并声明所有变量
    4. 我喜欢A Select Case 在函数中 If 语句,特别是如果要添加更多的条件,而您可能需要多个条件的相同结果。

    代码:

    Option Explicit
    
    Public Sub DoSomeThing()
        Dim dict As Object, arr2, m As Long, key As Variant
        arr2 = aaa  '<==Set one array equal to the other (no set keyword as not object)
    
        For m = LBound(arr2) To UBound(arr2)
           If TypeName(arr2(m)) = "Dictionary"  ' <== We can test if current array item is a dictionary before attempting the set. You have only added dictionaries at position 1 and 2 in the array. Less robust would be If m = 1 Or m = 2
                Set dict = arr2(m)   '<==index into your arr2 array
                For Each key In dict.Keys
                    Debug.Print dict(key)
                Next key
            End If
        Next
    End Sub
    
    Public Function aaa() As Variant
       Dim arr(5), k As Long, val1 As Long, val2 As Long, dict_123 As Object
       For k = 1 To 2
           Select Case k '<== Use select statement 
           Case 1
               val1 = 300
               val2 = 500
           Case 2
               val1 = 600
               val2 = 1200
          End Select
          Set dict_123 = CreateObject("Scripting.Dictionary")
          dict_123.Add "first", val1
          dict_123.Add "Second", val2
          Set arr(k) = dict_123 'K starts at 1 so position 0 is empty; as are positions after 2.
       Next k
       aaa = arr
    
    End Function