问题描述
我需要在数组中添加变量
I need to add the var in array
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
在 test(iCounter) = "test"
请提出一些解决方案
推荐答案
通常,您应该声明特定类型的变量,而不是Variant
.在这个例子中,test
变量应该是 String
类型.
Generally, you should declare variables of a specific type, rather than Variant
. In this example, the test
variable should be of type 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:
如果您在编写程序时知道数组的大小(它应该包含的元素数量),您可以在声明中的括号中指定该数量:
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.
如果在编写应用程序时不知道数组的大小,可以使用动态数组.动态数组的大小未在声明(Dim
语句)中指定,而是在程序执行期间使用 ReDim
语句确定.例如:
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 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
这篇关于如何在 VBA 中声明数组变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!