当设置数组等于一个范围时,下标超出范围VBA错误

目前,我有一系列的string,我希望能够进入一个数组。 然而,我不确定它是否工作,每次我尝试对数组做任何事情,我都会得到一个下标超出范围的错误。 我试着只是做一个Debug.Print,看看值是否进入数组或不,但导致相同的错误。 这是我到目前为止..

UsedRow = ActiveWorkbook.Sheets(3).UsedRange.Rows.Count Dim ProjectCounter As Long Dim ArrRange As Range 'This determines the number of entries in the array (I know this part works) i = UsedRow ProjectCounter = 0 Do While Cells(i, 1).FormulaR1C1 <> vbNullString ProjectCounter = ProjectCounter + 1 i = i - 1 Loop 'Array should have dimensions that match the number of projects Dim ProjectArray() As Variant ReDim ProjectArray(ProjectCounter - 1) 'Set range for array to cover Set ArrRange = ActiveWorkbook.Sheets(3).Range("A" & UsedRow - ProjectCounter & ":A" & UsedRow) 'Populate array with projects ProjectArray = ArrRange For i = LBound(ProjectArray) To UBound(ProjectArray) Debug.Print ProjectArray(i) Next 

这是build立一个数组的正确方法吗? 如果不是,我做错了什么? 谢谢。

您可以将数组读入预设范围而无需重新设定。 声明不带括号的变体。

 Dim ProjectArray as Variant ProjectArray = ArrRange 

你得到错误,因为你的数组有2个维度。 你需要

 for I = 1 to ubound(ProjectArray) debug.print ProjectArray(I,1) next I 

当你这样做时,LBound总是1。

我一直认为一维范围被复制为二维数组的方式是VBA中最令人讨厌的事情之一。 一种修正生成的下标超出范围错误的方法是,而不是记住包括一个无意义的下标,首先修复数组本身,所以如果数组在概念上是一维的,那么你的代码可以这样对待它。 下面的子修改了当你给variables赋值的范围时你得到的数组types。 如果它真的是二维的,就不会采取任何行动:

 Sub FixArray(valArray As Variant) 'As Variant 'This sub takes a pseudo 2-dimenional 1-based variant array 'And makes it 1-dimensional Dim fixedArray As Variant Dim columnVector As Boolean Dim i As Long, m As Long, n As Long On Error GoTo err_handler m = UBound(valArray, 1) n = UBound(valArray, 2) 'will throw an error if already 1-dimensional If m > 1 And n > 1 Then Exit Sub 'can't be fixed without losing data If m > 1 Then columnVector = True Else columnVector = False m = n End If ReDim fixedArray(1 To m) For i = 1 To m If columnVector Then fixedArray(i) = valArray(i, 1) Else fixedArray(i) = valArray(1, i) End If Next i valArray = fixedArray err_handler: 'no action - nothing to fix End Sub 

testing子(在debugging模式下运行,打开本地窗口并查看v如何从2维变为1维):

 Sub test() Dim v As Variant v = Range("A1:A3").Value FixArray v Debug.Print "here" 'convenient breakpoint End Sub