从范围值VBA创建数组

时间:2018-10-24 08:35:41

标签: arrays excel vba excel-vba

我试图做一个宏,我需要一个值数组。 此数组是根据范围可变的范围创建的。 我已经尝试了以下方法,但仍然出现错误:

Sub chase()


Dim rng As Range
Dim myarray() As Variant

last = Range("r1").End(xlDown).Address
MsgBox last

myarray = Range("r1:" & last).Value
For i = LBound(myarray) To UBound(myarray)
        msg = msg & myarray(i) & vbNewLine
    Next i
MsgBox "the values of my dynamic array are: " & vbNewLine & msg


End Sub

知道如何处理吗?

谢谢

2 个答案:

答案 0 :(得分:1)

使用范围分配中的最后一行。

dim last as long

last = Range("r1").End(xlDown).row
myarray = Range("r1:r" & last).Value

您正在创建二维数组。尽管某些功能默认情况下排在第一位,但最好将二维数组视为二维数组。

For i = LBound(myarray, 1) To UBound(myarray, 1)
        msg = msg & myarray(i, 1) & vbNewLine
Next i

答案 1 :(得分:1)

请参见下文:

Sub chase()

  Dim i As Integer, msg As String
  Dim last As Variant
  Dim rng As Range
  Dim myarray As Variant

  last = Sheet1.Range("r1").End(xlDown).Address
  MsgBox last

  myarray = Sheet1.Range("r1:" & last).Value
  For i = LBound(myarray) To UBound(myarray)
    msg = msg & myarray(i, 1) & vbNewLine
  Next i

  MsgBox "the values of my dynamic array are: " & vbNewLine & msg

End Sub