请问有谁可以解释这个错误的原因是什么?代码看起来对我很好。
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
答案 0 :(得分:1)
您已将prodCode声明为字符串,但不是字符串数组。
如果您希望将该变量用作数组,则需要使用prodCode() As String
。
注意:您还可以使用Variant数组来加速代码,然后允许您加载"加载"一次传输操作中的数组:
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
已被用于将数组的形状从1 To n, 1 To 1
二维数组更改为1 To n
一维数组。