将所有行和两列数据分配给数组

时间:2015-05-29 22:05:30

标签: excel vba excel-vba

我正在尝试从两列返回未知数量[8行]的所有数据行。对于>>我的下标超出范围错误SERnumber(rws, clm)

我只是想回来:

in  AAA
out AAA
in  AAA
in  VVV
in  GGG

这是我的非工作代码:

Sub Button1_Click()
Dim SERnumber() As String
Dim i As Integer
Dim strMessage As String
Dim rws As Integer
Dim clm As Integer
' assign variable > rws the # of rows containing data
         rws = Cells(Rows.Count, 2).End(xlUp).Row
' Redimension the SERnumber array variable >>
' for n? rows and 2 columns
         ReDim SERnumber(1 To rws, clm)

         For i = 1 To rws
               For clm = 1 To 2
                  SERnumber(rws, clm) = Cells(rws, clm).Value
               Next clm
         Next i
' Loop through the array and add the names to a string
        strMessage = "Here are the results:" & vbCrLf
            For i = 0 To rws
               strMessage = strMessage & SERnumber(i) & vbCrLf
            Next 'i
        MsgBox strMessage
End Sub

1 个答案:

答案 0 :(得分:1)

您可以将Excel Range分配给VBA Array对象,如以下VBA代码示例所示(Range包括整个A列和B列):

Sub Range2Array()
    Dim arr As Variant
    arr = Range("A:B").Value
    'alternatively
     'arr = Range("A:B")
    'test
    Debug.Print (arr(1, 1))
End Sub

与使用Range迭代相比,对2d阵列的这种直接分配具有巨大的性能优势。然后,您可以对数组元素而不是范围单元格执行所有必要的操作(与迭代范围操作相比,它也会非常快。)

另一个有用的技术是将Excel的UsedRange分配给VBA数组:

arr = ActiveSheet.UsedRange

而且,最简单的例子(与你的2列,8行相关):

arr = Range("A1:B8").Value

希望这会有所帮助。最好的问候,