将VBA数组分配给新变量

时间:2017-12-11 11:04:19

标签: vba multidimensional-array

我正在尝试将一个二维Variant数组分配给一个变量,由于某种原因它不起作用。

Function getClusters() As Variant()

Dim numberOfClusters, numberOfDifferentPartsPlusCaption, i, k As Integer
Dim clusters_() As Variant

numberOfClusters = Worksheets("Cluster Definition xy").UsedRange.Columns(Worksheets("Cluster Definition xy").UsedRange.Columns.Count).column - 1
numberOfDifferentPartsPlusCaption = Worksheets("Cluster Definition xy").UsedRange.Rows(Worksheets("Cluster Definition xy").UsedRange.Rows.Count).Row - 4

ReDim clusters_(numberOfClusters - 1, numberOfDifferentPartsPlusCaption)

For i = 0 To numberOfClusters - 1
   clusters_(i, 0) = Worksheets("Cluster Definition xy").Cells(3, i + 2)

   For k = 1 To numberOfDifferentPartsPlusCaption
     clusters_(i, k) = Worksheets("Cluster Definition xy").Cells(k + 4, i + 2)
   Next   

Next

getClusters = clusters_
'WriteArrayToImmediateWindow (getClusters)

End Function

初始化用户窗体时会调用该函数,并且应该可以正常工作,结果如下所示:

数组截图

Array screenshot

错误发生在" clusters = getClusters()"并表示类型不匹配。

Private Sub UserForm_Initialize()

Dim clusters() as Variant
Dim numberOfClusters, i As Integer
'ReDim clusters(UBound(getClusters(), 1) - LBound(getClusters(), 1), UBound(getClusters(), 2) - LBound(getClusters(), 2))

clusters = getClusters()

numberOfClusters = UBound(clusters, 1) - LBound(clusters, 1) + 1

For i = 0 To numberOfClusters
  something
Next

End Sub

我做错了什么?我担心我在这里遗漏了一些非常基本的东西。

提前多多感谢!

0 个答案:

没有答案