VBA Excel在MSGBOX中显示值

时间:2016-10-10 11:04:59

标签: vba excel-vba excel

我正在尝试创建一个简单的Sub,它可以抓取一系列数据并将其显示在MSGBox中。当我运行代码时,我收到运行时错误“9”:下标超出范围。有人可以协助吗?

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

2 个答案:

答案 0 :(得分:1)

转换为数组时Range为2维,因此最终得到searchContent(1 to 10, 1 To 1).

要在循环中阅读此内容:

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

答案 1 :(得分: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