【问题标题】:Copy 1D array to multidimensional array - VBA将一维数组复制到多维数组 - VBA
【发布时间】:2016-03-30 13:56:07
【问题描述】:

我在 VBA 中有两个函数。 Function1 返回一个一维数组。然后我有function2,它是一个多维数组。我想将 Function1 中的数组复制到从索引 1 开始的多维数组的列中。

arr2(0,0) = "Something"
arr2(0,1) = ("Something",arr1(0))
arr2(0,2) = ("Something",arr1(1))

这就是我所拥有的。 arr1 是 GetRecData,arr2 是 AllChannelsData。

For i = 0 To UBound(channelList)
    'the first row in the array is the channels names
    AllChannelsData(i, 0) = channelList(i)
    Set RecChannel = Rec.FindChannel(channelList(i), RecDevice.Name)
    For j = 0 To total_time
        AllChannelsData(i, j + 1) = RecChannelData.GetRecData(RecChannel, 1, 0)
    Next
Next

谢谢!

【问题讨论】:

    标签: arrays vba excel multidimensional-array


    【解决方案1】:

    请参考下面的代码。

    Sub Array_test()
        Dim GetRecData(9) As String
        Dim AllChannelsData(9, 2) As String
        For i = 0 To 9
            GetRecData(i) = i
            For j = 0 To 9
                AllChannelsData(j, 0) = j
                AllChannelsData(j, 1) = GetRecData(j)
            Next j
        Next i
    End Sub
    

    【讨论】:

      【解决方案2】:

      改变这个:

      For j = 0 To total_time
          AllChannelsData(i, j + 1) = RecChannelData.GetRecData(RecChannel, 1, 0)
      Next
      

      到这里

      For j = 0 To total_time
          AllChannelsData(i, j + 1) = RecChannelData.GetRecData(RecChannel, 1, j)
      Next
      

      也许?

      我假设.GetRecData(RecChannel, 1, 0) 方法的第三个参数是索引,因为像您描述的一维数组不采用 3 个参数。如果不是这样,您可能需要扩展 GetRecData 方法是/does/returns/etc。

      【讨论】:

      • 感谢您的快速回复。第三个参数不是索引。 GetRecData 方法需要三个参数才能返回一维数组。
      【解决方案3】:

      这个“基本”代码有效

      Option Explicit
      
      Sub main()
      Dim arr1 As Variant
      Dim arr2() As Variant
      Dim total_time As Integer, i As Integer, j As Integer
      
      total_time = 4
      
      ReDim arr2(0 To 3, 0 To total_time)
      For i = 0 To 3
          arr2(i, 0) = i
          For j = 1 To total_time
              arr2(i, j) = GetRecData(j + 1)
          Next j
      Next i
      
      End Sub
      
      Function GetRecData(n As Integer) As Variant
      ReDim arr(0 To n - 1) As Variant
      Dim i As Integer
      
      For i = 1 To n
          arr(i - 1) = i
      Next i
      
      GetRecData = arr
      End Function
      

      根据您的需要调整它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-12-19
        • 1970-01-01
        • 2021-12-31
        • 1970-01-01
        • 2015-06-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多