2017-02-16 150 views
1

任何人都可以請解釋什麼是這個錯誤的原因?代碼對我來說看起來非常好。編譯錯誤:預期的數組 - VBA

Public n As Long, i As Long, prodCode As String 
Private Sub newArray() 

    n = wsProducts.Range("A1", wsProducts.Range("A1").End(xlDown)).Rows.Count 

    ReDim prodCode(n) 

    For i = 1 To n 
     prodCode(i) = wsProducts.Range("A1").Offset(i, 0) 
    Next i 

End Sub 
+6

您已經將'prodCode'聲明爲一個字符串,但不是一個字符串數組 – YowE3K

+2

'prodCode()As String' –

+0

@ YowE3K謝謝!那太簡單了! –

回答

1

您已經聲明prodCode作爲一個字符串,而不是作爲一個字符串數組。如果您希望將該變量用作數組,則需要使用prodCode() As String


注:

Public n As Long, prodCode() As Variant 
Private Sub newArray() 

    n = wsProducts.Range("A1", wsProducts.Range("A1").End(xlDown)).Rows.Count 
    'P.S. That statement would simplify to 
    'n = wsProducts.Range("A1").End(xlDown).Row 

    prodCode = Application.Transpose(wsProducts.Range("A1:A" & n) 

End Sub 

Application.Transpose已被用來改變:您還可以通過使用一個Variant數組,它允許你再到「負荷」在一次傳送中操作陣列加快你的代碼了數組的形狀從一個1 To n, 1 To 1二維數組到一個1 To n一維數組。