目前,我有一系列我希望能夠輸入到數組中的字符串。但是,我不確定它是否正常工作,並且每次我嘗試對該數組執行任何操作時,都會得到下標超出範圍錯誤。我試着做一個Debug.Print來查看值是否進入數組,但是導致相同的錯誤。這是我到目前爲止..當設置一個等於一個範圍的數組時,下標超出範圍VBA錯誤
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
這是正確的方式來設置數組?如果不是,我做錯了什麼?謝謝。
也許嘗試'ReDim ProjectArray(ProjectCounter - 1,1)'?範圍映射回二維VBA數組。您也可以嘗試完全刪除'ReDim'語句 – Ioannis
我已嘗試刪除ReDim,並導致錯誤。我認爲,因爲你不能有Dim ProjectArray(someVariable),它必須是一個常量。不幸ReDim ProjectArray(ProjectCounter - 1,1)也沒有工作。 –
奇怪的是,它不工作[沒有'ReDim'](http://www.cpearson.com/excel/ArraysAndRanges.aspx)..我認爲數組的長度是ProjectCounter(不是ProjectCounter - 1),所以確實如此也不會工作。順便說一句,刪除'ReDim'會讓它變暗'Dim ProjectArray()作爲Variant',不需要一個常量 – Ioannis