2016-10-10 133 views
0

我正在嘗試創建一個簡單的Sub來抓取一系列數據並將其顯示在MSGBox中。當我運行代碼時,我收到運行時錯誤'9':下標超出範圍。有人能幫忙嗎?VBA Excel在MSGBOX中顯示值

Sub main() 

Dim ws1 As Worksheet 
Dim searchContent As Variant 
Dim i As Integer 
Dim txt As String 

Set ws1 = ThisWorkbook.Worksheets("Sheet1") 
searchContent = ws1.Range("B2:B11").Value 

For i = 1 To 10 
    txt = txt & searchContent(i) & vbCrLf 
Next i 

MsgBox (txt) 

End Sub 

回答

1

一個Range時轉換爲一個數組是二維的,所以你最終與searchContent(1 to 10, 1 To 1).

要在循環中讀取這樣的:

txt = txt & searchContent(i, 1) & vbCrLf 
+0

謝謝你做到了! –

1

如果你要保持你的數組作爲一個(因爲您正嘗試讀取單個列的範圍),您可以使用以下代碼:Application.Transpose

Sub main() 

Dim ws1     As Worksheet 
Dim searchContent  As Variant 
Dim i     As Integer 
Dim txt     As String 

Set ws1 = ThisWorkbook.Worksheets("Sheet1") 

searchContent = Application.Transpose(ws1.Range("B2:B11").Value) 

For i = 1 To UBound(searchContent) 
    txt = txt & searchContent(i) & vbCrLf 
Next i 

MsgBox (txt) 

End Sub 
+0

感謝您的替代解決方案! –