繁体   English   中英

VBA / Excel:“下标超出范围”错误

[英]VBA/Excel: “Subscript out of range” error

我试图用特定单元格是否为空的值填充Hrs数组:

Sub Add_training_hrs()
    Dim Rng1, Rng2 As Range
    Dim m, n As Integer
    Dim Hrs() As Double

    Set Rng11 = Application.InputBox("Upper-left cell (e.g., C4): ", "Box #1", Type:=8)
    Set Rng22 = Application.InputBox("Lower-right cell: ", "Box #2", Type:=8)

    Col11 = Rng11.Column
    Row11 = Rng11.Row
    Col22 = Rng22.Column
    Row22 = Rng22.Row

    nRows = Row22 - Row11
    nCols = Col22 - Col11

    ReDim Hrs(1 To nCols)

    Debug.Print "Hrs(1) = "; Hrs(1)

    For n = 1 To nRows
        For m = 1 To nCols
            If IsEmpty(Cells(n, m).Value) Then
                Hrs(m) = 0
                Debug.Print "Hrs(m) = "; Hrs(m)
            Else
                Hrs(m) = Cells(Row11 - 1, m).Value
            End If
        Cells(n, Col22 + 1).Value = Application.Sum(Hrs)
        Erase Hrs
        Next m
    Next n
End Sub

由于某种原因, If... ThenHrs(m) = 0 If... Then语句之后,我一直收到“ Subscription out ...”错误,但我不知道为什么。 感谢您提供任何建议,如果有重复的问题可以帮助您,请随时让我知道(我看过...)。


更新(和工作)的代码

我的原始脚本存在各种问题,但我可以使用它。 我将其张贴在这里,以防他人使用:

Sub Add_training_hrs()
    Dim Rng11 As Range
    Dim Rng22 As Range
    Dim m As Integer
    Dim n As Integer
    Dim Hrs() As Double

    Set Rng11 = Application.InputBox("Upper-left cell (e.g., C4): ", "Box #1", Type:=8)
    Set Rng22 = Application.InputBox("Lower-right cell: ", "Box #2", Type:=8)

    Col11 = Rng11.Column
    Row11 = Rng11.Row
    Col22 = Rng22.Column
    Row22 = Rng22.Row

    nRows = (Row22 - Row11) + 1
    nCols = (Col22 - Col11) + 1

    ReDim Hrs(1 To nCols)

    For n = 0 To nRows - 1
        For m = 0 To nCols - 1
            If IsEmpty(Cells(Row11 + n, Col11 + m).Value) Then
                Hrs(m + 1) = 0
            Else
                Hrs(m + 1) = Cells(Row11 - 1, Col11 + m).Value
            End If
        Next m
        Cells(Row11 + n, Col22 + 1).Value = Application.Sum(Hrs)
        Erase Hrs
        ReDim Hrs(1 To nCols)
    Next n
End Sub

我想您只会从第二行开始出现错误。

擦除动态数组时,您正在释放内存(请参见擦除

之后,您将需要重新分配它。

暂无
暂无

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

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