3
我希望创建一个简单的双精度VBA数组,但我希望数组的长度由工作表的单元格值指定。取决于用户输入的VBA数组长度
我尝试这样做:
Dim NIteration As Integer: NIteration = ActiveSheet.Cells(16, 2).Value
Dim myArray(1 To NIteration) As Double
它失败,此错误:“需要常量表达式”
我希望创建一个简单的双精度VBA数组,但我希望数组的长度由工作表的单元格值指定。取决于用户输入的VBA数组长度
我尝试这样做:
Dim NIteration As Integer: NIteration = ActiveSheet.Cells(16, 2).Value
Dim myArray(1 To NIteration) As Double
它失败,此错误:“需要常量表达式”
这听起来像你想利用VB的Redim
关键字。
Redim允许您在运行时将数组大小重新定义为给定的上限。
动态数组变量
动态数组变量是当你事先不知道你需要存储有关的信息有多少元素有用。
除非您不提供有关数组大小的任何信息,否则就像静态数组变量一样声明动态数组变量。
举个例子,如果您有:如果张数超过10,因为SheetNames将不能超过10项存储库的集合中
Dim SheetNames(1 to 10) As String
错误将被抛出。
相反,我们使用如下的redim
关键字:
Sub Test()
Dim MyArray() As String ' declare an array
Dim iCount As Integer
Dim Max As Integer
Max = ActiveSheet.Cells(16, 2).Value ' finds the maximum array size
ReDim MyArray(1 To Max) ' redeclares the array variable with the necessary size
For iCount = 1 To Max
MyArray(iCount) = ThisWorkbook.Sheets(iCount).Name ' (or whatever you're storing in the array)
MsgBox MyArray(iCount)
Next iCount
Erase MyArray() ' deletes the variable contents
End Sub
谢谢,这是现货! – Jamesszm
我认为这会工作'昏暗myArray的(NIteration)为Double'。如果不是,Phil有完整的细节。 – L42
经过测试,这不起作用 – Jamesszm