繁体   English   中英

将数组设置为范围时下标超出范围VBA错误

[英]Subscript out of range VBA error when setting an array equal to a range

目前,我想输入一个范围很广的字符串。 但是,我不确定它是否有效,并且每次尝试对数组执行任何操作时,都会收到下标超出范围的错误。 我尝试仅执行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

这是建立阵列的正确方法吗? 如果没有,我在做什么错? 谢谢。

长期以来,我一直认为将一维范围复制为二维数组的方式是有关VBA的最烦人的事情之一。 修复结果下标超出范围错误的一种方法是,而不是记住包括一个无意义的下标,首先修复数组本身,这样,如果数组在概念上是一维的,则您的代码可以将其视为此类。 以下子项修改了在为变量分配值范围时获得的数组类型。 如果它是真正的二维,则不执行任何操作:

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

一个测试子(在调试模式下运行,打开“本地”窗口,并查看v如何从2维变为1维):

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

您可以将数组读取到预设范围内,而无需重新调整。 声明不带括号的变量。

Dim ProjectArray as Variant
ProjectArray = ArrRange

因为数组有2个维,所以会出现错误。 你需要

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

这样,LBound将始终为1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM