类型不匹配存储VBA数组中的单元格值

时间:2013-05-30 13:17:19

标签: arrays excel types mismatch

这适用于MsgBox,但是当我取消对赋值语句的注释时,我得到了类型不匹配错误。我有一个未知的字符串长度,从D1开始,我想存储在数组MyArr中。

Dim MyArr As Variant   
Range("D1").Select
I = 1

While ActiveCell <> Empty
    MsgBox ("this is in the active cell:" & ActiveCell.Value)
'   MyArr(I) = ActiveCell.Value
    I = I + 1
    ActiveCell.Offset(1, 0).Select
Wend

1 个答案:

答案 0 :(得分:1)

MyArr(I)将失败,因为MyArr尚未定义为数组。看看你的代码,你似乎希望MyArr包含从D1找到的所有字符串到第一个空单元格

Dim MyArr
MyArr=Range("D1", Range("D1").End(xlDown))
If VarType(MyArr)>vbArray then 'more than 1 cell returned
    'D1 is in MyArr(1,1)
    'D2 is in MyArr(2,1)
    '...
    'Lastcell is in MyArr(Ubound(MyArr),1)
Else 'Only one cell found with text
    'D1 is in MyArr 
    'note no () -> one cell = no array
End If