【问题标题】:VBA first array item is always emptyVBA 第一个数组项始终为空
【发布时间】:2018-02-10 21:56:01
【问题描述】:

下面的代码是我从网上找到的几个示例中修补的,我不是 VBA 专家。

clist 数组中的第一项(以及下拉列表中的第一项)始终为空,我假设它与redims 有关,但我无法弄清楚.

可能是什么问题?

Private Sub ComboBox1_Change()
    ReDim clist(0)
    'If any value is input
    If ComboBox1.Value <> "" Then
        Dim kword As Variant
        Dim product As Variant
        'For each product description in our sheet table
        For Each product In [Produtos[Descrição]].Rows
            'Keyword search
            For Each kword In Split(ComboBox1.Value, " ")
                If InStr(Replace(product.Value, "", " "), kword) And kword <> "" Then
                    'Issue most likely here
                    ReDim Preserve clist(UBound(clist) + 1) As Variant
                    clist(UBound(clist)) = product.Value
                    Exit For
                End If
            Next kword
        Next product
        ComboBox1.list = clist
        'If found something
        If UBound(clist) > 0 Then
            ComboBox1.DropDown
        End If
    'If no Input just show all products, here it doesn't show a blank item
    Else
        ComboBox1.list = [Produtos[Descrição]].Value2
    End If
End Sub

【问题讨论】:

    标签: arrays vba excel loops


    【解决方案1】:

    试试看,

        ReDim clist(0)
        For Each product In [Produtos[Descrição]].Rows
            'Keyword search
            For Each kword In Split(ComboBox1.Value, " ")
                If InStr(Replace(product.Value, "", " "), kword) And kword <> "" Then
                    'Issue most likely here
                    clist(UBound(clist)) = product.Value
                    ReDim Preserve clist(UBound(clist) + 1)
                    Exit For
                End If
            Next kword
        Next product
        ReDim Preserve clist(UBound(clist) - 1)
    

    【讨论】:

    • 如果 clist 的大小从不增加,则会出错
    【解决方案2】:

    这是因为您正在增加数组的大小,然后才为它的最后一个索引设置一个值。

    ReDim Preserve clist(UBound(clist) + 1) As Variant 'Increase array size by 1
    clist(UBound(clist)) = product.Value 'Set a value to the higher index
    

    这样你就永远不会为index 0设置值

    这样的事情应该可以解决你的问题:

    if clist(Ubound(clist)) <> empty then
        ReDim Preserve clist(UBound(clist) + 1) As Variant
    end if
    clist(UBound(clist)) = product.Value
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-04
      • 2014-10-04
      • 2017-01-07
      • 1970-01-01
      • 2021-02-24
      • 2012-10-09
      • 1970-01-01
      相关资源
      最近更新 更多