Excel - VBA将矩阵条目转换为行总计的百分比

时间:2016-01-04 21:48:51

标签: arrays excel vba matrix

我有一个矩阵,其行数和列数相同,大小为 numColors 。以下代码尝试将每个条目从整数转换为其行总数的百分比。我收到“下标超出范围”错误,需要帮助修复它。感谢。

Screenshot of the Excel matrix

Screenshot of the desired output matrix

For i = 2 To numColors + 2
rowSum = 0
tempArray = Range(Cells(i, 2), Cells(i, numColors + 1))
    For j = LBound(tempArray) To UBound(tempArray)
        rowSum = rowSum + tempArray(j)
    Next
    For j = LBound(tempArray) To UBound(tempArray)
        tempArray(j) = tempArray(j) / rowSum
    Next
Range(Cells(i, 2), Cells(i, numColors + 1)) = tempArray
Next

1 个答案:

答案 0 :(得分:0)

试试这个:

For i = 2 To numColors + 1
    rowSum = 0
    tempArray = Range(Cells(i, 2), Cells(i, numColors + 1))
    For j = LBound(tempArray, 2) To UBound(tempArray, 2)
        rowSum = rowSum + tempArray(1, j)
    Next j
    For j = LBound(tempArray, 2) To UBound(tempArray, 2)
        tempArray(1, j) = tempArray(1, j) / rowSum
    Next j
    Range(Cells(i, 2), Cells(i, numColors + 1)) = tempArray
Next i

原因是即使它是一行,tempArray也是一个2D数组。

以下是对代码的略微修改。它将整个矩阵加载到数组中,操纵数据然后将值作为一个整体返回:

tempArray = Range(Cells(2, 2), Cells(numColors + 1, numColors + 1))
For i = LBound(tempArray, 1) To UBound(tempArray, 1)
    rowSum = 0
    For j = LBound(tempArray, 2) To UBound(tempArray, 2)
        rowSum = rowSum + tempArray(i, j)
    Next j
    For j = LBound(tempArray, 2) To UBound(tempArray, 2)
        tempArray(i, j) = tempArray(i, j) / rowSum
    Next j
Next i
Range(Cells(2, 2), Cells(numColors + 1, numColors + 1)).value = tempArray

在这种情况下,速度不会有太大差异,但如果矩阵越大,参考电子表格的次数越少越好。