创建具有可变数量元素的数组变量

时间:2013-08-23 18:28:58

标签: arrays vba variables dynamic constants

我想定义一个数组变量,使其具有可变数量的元素,具体取决于从搜索返回的m个结果数。我在“

>上收到错误”需要常量表达式“
Dim cmodels(0 To m) As String

这是我的完整代码

Dim foundRange As Range
Dim rangeToSearch As Range
Set rangeToSearch = Selection
Set foundRange = rangeToSearch.Find(What:="Lights", After:=ActiveCell,            
LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
, SearchFormat:=False) 'First Occurrence
    m = WorksheetFunction.CountIf(Selection, "Lights")
 Dim secondAddress As String
If (Not foundRange Is Nothing) Then
    Dim count As Integer: count = 0
    Dim targetOccurrence As Integer: targetOccurrence = 2
    Dim found As Boolean
    z = 1
    Dim cmodels(0 To m) As String
    Do Until z = m
    z = z + 1
        foundRange.Activate
        Set foundRange = rangeToSearch.FindNext(foundRange)
        If Not foundRange.Next Is Nothing Then
        z(m) = ActiveCell(Offset(0, 2))
        End If
    Loop
    End If
End Sub

2 个答案:

答案 0 :(得分:3)

请参阅以下代码注释:

Sub redimVsRedimPreserve()

    'I generally declare arrays I know I will resize
    'without a fixed size initially..
    Dim cmodels() As String
    Dim m As Integer
    m = 3

    'this will wipe out all data in the array
    ReDim cmodels(0 To m) As String

    'you can also use this if you want to save all information in the variable
    cmodels(2) = "test"
    ReDim Preserve cmodels(0 To m) As String

    'this will still keep "test"
    Debug.Print "With redim preserve, the value is: " & cmodels(2)

    'using just 'redim'
    ReDim cmodels(0 To m) As String
    Debug.Print "with just redim, the value is: " & cmodels(2)



End Sub

另请注意,经常使用Redim Preserve(例如循环)可能需要一些时间。

答案 1 :(得分:1)

Dim cmodels() As String
'...
ReDim cmodels(0 to m)