2

我想定义一个数组变量,使其具有可变数量的元素,具体取决于从搜索返回的 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
4

2 回答 2

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频繁使用(例如循环)可能是一项需要一些时间的操作。

于 2013-08-23T18:34:30.777 回答
1
Dim cmodels() As String
'...
ReDim cmodels(0 to m)
于 2013-08-23T18:32:11.060 回答