如何在VBA中声明数组变量?

时间:2022-05-11 00:28:43

I need to add the var in array

我需要在数组中添加var

Public Sub Testprog()

Dim test As Variant
Dim iCounter As Integer

If test = Empty Then
    iCounter = 0
    test(iCounter) = "test"
Else
    iCounter = UBound(test)
End If
End Sub

Getting error at test(iCounter) = "test"

测试时出错(iCounter)=“测试”

Please suggest some solution

请提出一些解决方案

7 个解决方案

#1


30  

Generally, you should declare variables of a specific type, rather than Variant. In this example, the test variable should be of type String.

通常,您应该声明特定类型的变量,而不是Variant。在此示例中,测试变量应为String类型。

And, because it's an array, you need to indicate that specifically when you declare the variable. There are two ways of declaring array variables:

并且,因为它是一个数组,所以在声明变量时需要明确指出。声明数组变量有两种方法:

  1. If you know the size of the array (the number of elements that it should contain) when you write the program, you can specify that number in parentheses in the declaration:

    如果在编写程序时知道数组的大小(它应包含的元素数),则可以在声明的括号中指定该数字:

    Dim test(1) As String   'declares an array with 2 elements that holds strings
    

    This type of array is referred to as a static array, as its size is fixed, or static.

    这种类型的数组称为静态数组,因为它的大小是固定的,或者是静态的。

  2. If you do not know the size of the array when you write the application, you can use a dynamic array. A dynamic array is one whose size is not specified in the declaration (Dim statement), but rather is determined later during the execution of the program using the ReDim statement. For example:

    如果在编写应用程序时不知道数组的大小,则可以使用动态数组。动态数组的大小未在声明(Dim语句)中指定,而是稍后在使用ReDim语句执行程序期间确定。例如:

    Dim test() As String
    Dim arraySize As Integer
    
    ' Code to do other things, like calculate the size required for the array
    ' ...
    arraySize = 5
    
    ReDim test(arraySize)  'size the array to the value of the arraySize variable
    

#2


12  

Further to Cody Gray's answer, there's a third way (everything there applies her as well):

继Cody Gray的回答之后,还有第三种方式(一切都适用于她):

You can also use a dynamic array that's resized on the fly:

您还可以使用动态调整大小的动态数组:

Dim test() as String
Dim arraySize as Integer

Do While someCondition
    '...whatever
    arraySize = arraySize + 1
    ReDim Preserve test(arraySize)
    test(arraySize) = newStringValue
Loop

Note the Preserve keyword. Without it, redimensioning an array also initializes all the elements.

请注意Preserve关键字。没有它,重新定义数组也会初始化所有元素。

#3


6  

As pointed out by others, your problem is that you have not declared an array

正如其他人所指出的,你的问题是你没有声明一个数组

Below I've tried to recreate your program so that it works as you intended. I tried to leave as much as possible as it was (such as leaving your array as a variant)

下面我尝试重新创建您的程序,以便它按预期工作。我试图尽可能多地离开(例如将数组作为变体)

Public Sub Testprog()
    '"test()" is an array, "test" is not
    Dim test() As Variant
    'I am assuming that iCounter is the array size
    Dim iCounter As Integer

    '"On Error Resume Next" just makes us skip over a section that throws the error
    On Error Resume Next

    'if test() has not been assigned a UBound or LBound yet, calling either will throw an error
    '   without an LBound and UBound an array won't hold anything (we will assign them later)

    'Array size can be determined by (UBound(test) - LBound(test)) + 1
    If (UBound(test) - LBound(test)) + 1 > 0 Then
        iCounter = (UBound(test) - LBound(test)) + 1

        'So that we don't run the code that deals with UBound(test) throwing an error
        Exit Sub
    End If

    'All the code below here will run if UBound(test)/LBound(test) threw an error
    iCounter = 0

    'This makes LBound(test) = 0
    '   and UBound(test) = iCounter where iCounter is 0
    '   Which gives us one element at test(0)
    ReDim Preserve test(0 To iCounter)

    test(iCounter) = "test"
End Sub

#4


5  

Further to RolandTumble's answer to Cody Gray's answer, both fine answers, here is another very simple and flexible way, when you know all of the array contents at coding time - e.g. you just want to build an array that contains 1, 10, 20 and 50. This also uses variant declaration, but doesn't use ReDim. Like in Roland's answer, the enumerated count of the number of array elements need not be specifically known, but is obtainable by using uBound.

继RolandTumble对Cody Gray答案的回答之后,两个很好的答案,这是另一种非常简单灵活的方式,当您在编码时知道所有阵列内容时 - 例如你只想构建一个包含1,10,20和50的数组。这也使用变量声明,但不使用ReDim。就像在Roland的回答中一样,数组元素数量的枚举计数不需要具体知道,但可以通过使用uBound获得。

sub Demo_array()
    Dim MyArray as Variant, MyArray2 as Variant, i as Long

    MyArray = Array(1, 10, 20, 50)  'The key - the powerful Array() statement
    MyArray2 = Array("Apple", "Pear", "Orange") 'strings work too

    For i = 0 to UBound(MyArray)
        Debug.Print i, MyArray(i)
    Next i
    For i = 0 to UBound(MyArray2)
        Debug.Print i, MyArray2(i)
    Next i
End Sub

I love this more than any of the other ways to create arrays. What's great is that you can add or subtract members of the array right there in the Array statement, and nothing else need be done to code. To add Egg to your 3 element food array, you just type

我比其他任何创建数组的方式都更喜欢这个。最棒的是你可以在Array语句中添加或减少数组的成员,而不需要对代码做任何其他事情。要将Egg添加到3元素食物阵列中,只需键入即可

, "Egg"

, “蛋”

in the appropriate place, and you're done. Your food array now has the 4 elements, and nothing had to be modified in the Dim, and ReDim is omitted entirely.

在适当的地方,你已经完成了。你的食物数组现在有4个元素,在Dim中没有任何东西需要修改,ReDim完全省略。

If a 0-based array is not desired - i.e., using MyArray(0) - one solution is just to jam a 0 or "" for that first element.

如果不需要基于0的阵列 - 即,使用MyArray(0) - 一种解决方案就是为第一个元素堵塞0或“”。

Note, this might be regarded badly by some coding purists; one fair objection would be that "hard data" should be in Const statements, not code statements in routines. Another beef might be that, if you stick 36 elements into an array, you should set a const to 36, rather than code in ignorance of that. The latter objection is debatable, because it imposes a requirement to maintain the Const with 36 rather than relying on uBound. If you add a 37th element but leave the Const at 36, trouble is possible.

注意,一些编码纯粹主义者可能会认为这很糟糕;一个公平的反对意见是“硬数据”应该在Const语句中,而不是在例程中的代码语句。另一个可能是牛肉,如果你将36个元素粘贴到一个数组中,你应该将const设置为36,而不是编码而忽略它。后一种反对意见是值得商榷的,因为它强制要求用36维持Const而不是依赖于uBound。如果添加第37个元素但将Const保留为36,则可能会出现问题。

#5


2  

You have to declare the array variable as an array:

您必须将数组变量声明为数组:

Dim test(10) As Variant

#6


-1  

David, Error comes Microsoft Office Excel has stopped working. Two options check online for a solution and close the programme and other option Close the program I am sure error is in my array but I am reading everything and seem this is way to define arrays.

大卫,错误来自Microsoft Office Excel已停止工作。两个选项在线检查解决方案并关闭程序和其他选项关闭程序我确定错误在我的数组中,但我正在阅读所有内容,似乎这是定义数组的方法。

#7


-3  

The Array index only accepts a long value.

Array索引只接受long值。

You declared iCounter as an integer. You should declare it as a long.

您将iCounter声明为整数。你应该声明它很长。

#1


30  

Generally, you should declare variables of a specific type, rather than Variant. In this example, the test variable should be of type String.

通常,您应该声明特定类型的变量,而不是Variant。在此示例中,测试变量应为String类型。

And, because it's an array, you need to indicate that specifically when you declare the variable. There are two ways of declaring array variables:

并且,因为它是一个数组,所以在声明变量时需要明确指出。声明数组变量有两种方法:

  1. If you know the size of the array (the number of elements that it should contain) when you write the program, you can specify that number in parentheses in the declaration:

    如果在编写程序时知道数组的大小(它应包含的元素数),则可以在声明的括号中指定该数字:

    Dim test(1) As String   'declares an array with 2 elements that holds strings
    

    This type of array is referred to as a static array, as its size is fixed, or static.

    这种类型的数组称为静态数组,因为它的大小是固定的,或者是静态的。

  2. If you do not know the size of the array when you write the application, you can use a dynamic array. A dynamic array is one whose size is not specified in the declaration (Dim statement), but rather is determined later during the execution of the program using the ReDim statement. For example:

    如果在编写应用程序时不知道数组的大小,则可以使用动态数组。动态数组的大小未在声明(Dim语句)中指定,而是稍后在使用ReDim语句执行程序期间确定。例如:

    Dim test() As String
    Dim arraySize As Integer
    
    ' Code to do other things, like calculate the size required for the array
    ' ...
    arraySize = 5
    
    ReDim test(arraySize)  'size the array to the value of the arraySize variable
    

#2


12  

Further to Cody Gray's answer, there's a third way (everything there applies her as well):

继Cody Gray的回答之后,还有第三种方式(一切都适用于她):

You can also use a dynamic array that's resized on the fly:

您还可以使用动态调整大小的动态数组:

Dim test() as String
Dim arraySize as Integer

Do While someCondition
    '...whatever
    arraySize = arraySize + 1
    ReDim Preserve test(arraySize)
    test(arraySize) = newStringValue
Loop

Note the Preserve keyword. Without it, redimensioning an array also initializes all the elements.

请注意Preserve关键字。没有它,重新定义数组也会初始化所有元素。

#3


6  

As pointed out by others, your problem is that you have not declared an array

正如其他人所指出的,你的问题是你没有声明一个数组

Below I've tried to recreate your program so that it works as you intended. I tried to leave as much as possible as it was (such as leaving your array as a variant)

下面我尝试重新创建您的程序,以便它按预期工作。我试图尽可能多地离开(例如将数组作为变体)

Public Sub Testprog()
    '"test()" is an array, "test" is not
    Dim test() As Variant
    'I am assuming that iCounter is the array size
    Dim iCounter As Integer

    '"On Error Resume Next" just makes us skip over a section that throws the error
    On Error Resume Next

    'if test() has not been assigned a UBound or LBound yet, calling either will throw an error
    '   without an LBound and UBound an array won't hold anything (we will assign them later)

    'Array size can be determined by (UBound(test) - LBound(test)) + 1
    If (UBound(test) - LBound(test)) + 1 > 0 Then
        iCounter = (UBound(test) - LBound(test)) + 1

        'So that we don't run the code that deals with UBound(test) throwing an error
        Exit Sub
    End If

    'All the code below here will run if UBound(test)/LBound(test) threw an error
    iCounter = 0

    'This makes LBound(test) = 0
    '   and UBound(test) = iCounter where iCounter is 0
    '   Which gives us one element at test(0)
    ReDim Preserve test(0 To iCounter)

    test(iCounter) = "test"
End Sub

#4


5  

Further to RolandTumble's answer to Cody Gray's answer, both fine answers, here is another very simple and flexible way, when you know all of the array contents at coding time - e.g. you just want to build an array that contains 1, 10, 20 and 50. This also uses variant declaration, but doesn't use ReDim. Like in Roland's answer, the enumerated count of the number of array elements need not be specifically known, but is obtainable by using uBound.

继RolandTumble对Cody Gray答案的回答之后,两个很好的答案,这是另一种非常简单灵活的方式,当您在编码时知道所有阵列内容时 - 例如你只想构建一个包含1,10,20和50的数组。这也使用变量声明,但不使用ReDim。就像在Roland的回答中一样,数组元素数量的枚举计数不需要具体知道,但可以通过使用uBound获得。

sub Demo_array()
    Dim MyArray as Variant, MyArray2 as Variant, i as Long

    MyArray = Array(1, 10, 20, 50)  'The key - the powerful Array() statement
    MyArray2 = Array("Apple", "Pear", "Orange") 'strings work too

    For i = 0 to UBound(MyArray)
        Debug.Print i, MyArray(i)
    Next i
    For i = 0 to UBound(MyArray2)
        Debug.Print i, MyArray2(i)
    Next i
End Sub

I love this more than any of the other ways to create arrays. What's great is that you can add or subtract members of the array right there in the Array statement, and nothing else need be done to code. To add Egg to your 3 element food array, you just type

我比其他任何创建数组的方式都更喜欢这个。最棒的是你可以在Array语句中添加或减少数组的成员,而不需要对代码做任何其他事情。要将Egg添加到3元素食物阵列中,只需键入即可

, "Egg"

, “蛋”

in the appropriate place, and you're done. Your food array now has the 4 elements, and nothing had to be modified in the Dim, and ReDim is omitted entirely.

在适当的地方,你已经完成了。你的食物数组现在有4个元素,在Dim中没有任何东西需要修改,ReDim完全省略。

If a 0-based array is not desired - i.e., using MyArray(0) - one solution is just to jam a 0 or "" for that first element.

如果不需要基于0的阵列 - 即,使用MyArray(0) - 一种解决方案就是为第一个元素堵塞0或“”。

Note, this might be regarded badly by some coding purists; one fair objection would be that "hard data" should be in Const statements, not code statements in routines. Another beef might be that, if you stick 36 elements into an array, you should set a const to 36, rather than code in ignorance of that. The latter objection is debatable, because it imposes a requirement to maintain the Const with 36 rather than relying on uBound. If you add a 37th element but leave the Const at 36, trouble is possible.

注意,一些编码纯粹主义者可能会认为这很糟糕;一个公平的反对意见是“硬数据”应该在Const语句中,而不是在例程中的代码语句。另一个可能是牛肉,如果你将36个元素粘贴到一个数组中,你应该将const设置为36,而不是编码而忽略它。后一种反对意见是值得商榷的,因为它强制要求用36维持Const而不是依赖于uBound。如果添加第37个元素但将Const保留为36,则可能会出现问题。

#5


2  

You have to declare the array variable as an array:

您必须将数组变量声明为数组:

Dim test(10) As Variant

#6


-1  

David, Error comes Microsoft Office Excel has stopped working. Two options check online for a solution and close the programme and other option Close the program I am sure error is in my array but I am reading everything and seem this is way to define arrays.

大卫,错误来自Microsoft Office Excel已停止工作。两个选项在线检查解决方案并关闭程序和其他选项关闭程序我确定错误在我的数组中,但我正在阅读所有内容,似乎这是定义数组的方法。

#7


-3  

The Array index only accepts a long value.

Array索引只接受long值。

You declared iCounter as an integer. You should declare it as a long.

您将iCounter声明为整数。你应该声明它很长。