【问题标题】:Creating an array variable with a variable number of elements创建具有可变数量元素的数组变量
【发布时间】:2013-08-26 21:35:55
【问题描述】:

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

【问题讨论】:

    标签: arrays vba variables dynamic constants


    【解决方案1】:

    见以下代码cmets:

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

    【讨论】:

    • 这已成为一个热门问题;感谢 enderland 的出色回应。
    【解决方案2】:
    Dim cmodels() As String
    '...
    ReDim cmodels(0 to m)
    

    【讨论】:

    • Dim cmodels as String()
    • Dim cmodels as String() 导致错误,Dim cmodels(m) As String 给出了与被询问相同的问题...
    • 对,现在注意了,它是VBA...不同于VB。
    猜你喜欢
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多