2017-09-01 38 views
3

下面的代碼是我在網上找到的幾個示例中修補過的,我不是VBA專家。VBA第一個數組項目始終是空的

但數組中的第一項(以及下拉菜單中的第一項)始終爲空,我假設它與redim s有關,但我無法弄清楚。

可能是什麼問題?

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 

回答

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 
4

嘗試,因爲,

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) 
+0

這給出了一個錯誤,如果CLIST永遠不會在尺寸增大 – Mojimi

相關問題