VBA - 用于创建 n × m 矩阵的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27788623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:42:47  来源:igfitidea点击:

VBA - Function for Creating an n by m Matrix

excelvbamatrix

提问by lb90

I am currently working with arrays and loops, and am trying to write a function that will output an n by m array (a matrix) with the numbers {1, 2, 3, ... , n*m}

我目前正在处理数组和循环,并且正在尝试编写一个函数,该函数将输出带有数字 {1, 2, 3, ... , n*m} 的 n × m 数组(矩阵)

I am trying to learn some basic VBA code, this is purely for educational purposes.

我正在尝试学习一些基本的 VBA 代码,这纯粹是出于教育目的。

This is what I have come up with:

这是我想出的:

Function createMatrix(n, m)    
Dim matrix(1 To n, 1 To m) As Integer    
x = 1    
For i = 1 To n
    For j = 1 To m        
        matrix(i, j) = x            
        x = (x + 1)            
    Next j
Next i   
createMatrix = matrix    
End Function

It returns #VALUE. I cannot understand why.

它返回#VALUE。我不明白为什么。

I got it to work at one point (creating a 3x3 matrix) by making it a function that did not take any variables and then initializing the matrix array by

我让它在某一时刻工作(创建一个 3x3 矩阵),方法是使它成为一个不接受任何变量的函数,然后通过

Dim matrix(1 to 3, 1 to 3) As Integer

replacing nand min the for loops with 3s.

更换nm在与3S循环。

So I guess the variables nand mare causing the problems, but don't know why.

所以我猜变量nm导致问题,但不知道为什么。

回答by Jason Faulkner

Array declarations mustbe static (where the bounds are defined by a hardcoded value); however you can resize them dynamically using the ReDimstatement.

数组声明必须是静态的(边界由硬编码值定义);但是您可以使用该ReDim语句动态调整它们的大小。

' Declare an array.
' If you want to size it based on variables, do NOT define bounds.
Dim matrix() As Integer
' Resize dynamically.
ReDim maxtrix(n, m)

Note that when you ReDim, all values will be lost. If you had values in matrixthat you wanted to keep, you can add the Preservekeyword:

请注意,当您使用 时ReDim,所有值都将丢失。如果您有matrix想要保留的值,则可以添加Preserve关键字:

ReDim Preserve matrix(n, m) ' Keep any existing values in their respective indexes.

回答by Leni Ohnesorge

You first need to declare array as dynamic array and then redim it to your dimension.

您首先需要将数组声明为动态数组,然后将其重新映射到您的维度。

Function createMatrix(n, m)
   Dim matrix() As Integer
   ReDim matrix(1 To n, 1 To m) As Integer
   x = 1

    For i = 1 To n
       For j = 1 To m
            matrix(i, j) = x
            x = (x + 1)
        Next j
    Next i

    createMatrix = matrix
End Function