2013-05-30 51 views
0

這適用於MsgBox,但不是當我取消註釋賦值語句時出現類型不匹配錯誤。我有一個未知長度的字符串,從D1開始,我想存儲在數組MyArr中。類型不匹配存儲在VBA數組中的單元格值

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 
+2

myArr,該(我)會失敗,因爲myArr,該還沒有被定義爲一個數組。如果你知道你的字符串集合的結束條件,那麼可以構建一個可以分配給數組的字段 – SeanC

回答

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

謝謝Sean!在我試圖在ELSE條件下訪問MyArr時工作但鎖定。嘗試了MyArr,MyArr(1)和MyArr(1,1),但一直鎖定。 –

+0

@MichaelDehnel:你的意思是鎖定? – shahkalpesh

+0

如果你到了else語句,那麼'MyArr'是要使用的變量,而不是'MyArr(...'。我會檢查你從VarType(MyArr)獲得的值,看它是否返回您希望的變量類型。[本頁](https://office.microsoft.com/zh-cn/access-help/vartype-function-HA001228932.aspx)會告訴您**返回的值是什麼VarType ** – SeanC