簡體   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