在VBA中重新规划multidimensional array的两个维度(为什么这里的解决scheme将不起作用)

首先,我将指出围绕重新调整multidimensional array的问题已经在这里进行了讨论和回答: Excel VBA – 如何重新生成二维数组? 。

我的问题是,我正在尝试应用这个答案,这不是很顺利! 问题在于调用函数。 如果我在调用函数之前调整数组的大小,Excel只会告诉我它不能分配给数组(可能是因为我没有告诉它要分配哪个元素)。 如果我没有预先确定数组的大小,那么当它正在寻找旧数组的维数时,这个函数就会崩溃,因为它根本没有。

我知道我可以通过颠倒数组的方式来做下面的事情,然后转置它,但是我需要进一步改变数组的两个维度,所以我试图让它在这里工作。

我承认我在这个代码中“失去了生存的意志”,因为我已经和这个代码做了几个星期的斗争,并且是一个非常业余的程序员,所以我意识到这可能是一个非常简单的答案,但我看不到它在这一刻。 任何帮助感激地收到。

这里是我的代码(Sub是从另一个子集调用的,其中定义了所有其他variables)

Sub CalculateRank(row, coln, TempSums, TempProducts, Lead_count) Dim Maj As Double Dim CompareCount As Integer Dim CompareArray(1, 1) '**I don't really want to dimension this array before the loop below. Maj = WorksheetFunction.Round(Range("FJudges") / 2, 0) For coln = 1 To Lead_count CompareCount = 0 For row = 1 To Lead_count If TempSums(row, coln) >= Maj Then CompareCount = CompareCount + 1 CompareArray = ReDimPreserve(CompareArray, CompareCount, 3) '**This is the line that is calling the function (copied directly from the bottom of the page linked above) and giving the error CompareArray(CompareCount, 1) = row CompareArray(CompareCount, 2) = TempSums(row, coln) CompareArray(CompareCount, 3) = TempProducts(row, coln) End If Next row Next coln End Sub 

在调用该函数之前,您需要将其设置为二维数组, 使用Redim语句而不是Dim 。 这个问题不在你正在使用的ReDimPreserve函数中,因为它需要一个input数组并从头开始返回另一个数组。 你的问题在赋值语句中:

 CompareArray = ... 

VBA不允许分配给一个静态数组 ,这是因为你声明为:

 Dim CompareArray(1, 1) 

您需要改为将其声明为dynamic数组 ,如下所示:

 Dim CompareArray() ' <--- Optional declaration ReDim CompareArray(0, 0) ' <--- First initialization should be with ReDim 

PS

  • 声明Dim CompareArray()是可选的,但被许多人认为是好的做法。 基本上,你可以省略它,直接使用ReDim声明(甚至可以使用Option Explicit )。 只要确保在同一个作用域中不存在其他具有相同名称的variables(如果Dim语句在那里,编译器会提醒)。

  • 我开始(0, 0)因为这是最小的大小,而不是(1, 1) (编辑:除非你使用的Option Base 1因为它出现在评论中)。