将所有行和两列数据分配给一个数组
我试图从两列返回未知数量的所有数据行[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
您可以将Excel Range
分配给VBA数组对象,如以下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
与使用范围迭代相比,这种直接分配到二维数组具有巨大的性能优势。 然后,您可以对数组元素执行所有必要的操作,而不是范围单元格(与迭代范围操作符相比,它也会非常快)。
另一个有用的技术是将Excel的UsedRange
分配给VBA数组:
arr = ActiveSheet.UsedRange
而且,最微不足道的例子(与你的情况2列,8行):
arr = Range("A1:B8").Value
希望这会有所帮助。 最好的祝福,