簡體   English   中英

數組-VBA中的下標超出范圍

[英]Array - Subscript out of range in VBA

我試圖將值存儲在數組中。 我面臨的問題是下標超出范圍。

這是代碼,

Sub Trial()

Dim HeaderArray() As Variant

Dim HeaderValue As String

Dim j As Long

Dim i as Long

set wk = Activeworkbook

lastrow_header_Config = Wk.Sheets("Config").Cells(Rows.Count, "W").End(xlUp).Row

j = 1

      For i = 2 To lastrow_header_Config

         HeaderValue = Wk.Sheets("Config").Range("W" & i).Value

             If HeaderValue <> "" Then

              HeaderArray(j - 1) = HeaderValue // Subscript out of range error

             j = j + 1

             End If

      Next

End Sub

我正在犯什么錯誤。 好心提醒。

您需要先聲明數組的大小,然后再嘗試將數據放入其中。 使用COUNTA查找包含您范圍內數據的像元數:

Sub Trial()

Dim HeaderArray() As Variant
Dim HeaderValue As String
Dim lastrow_Header_Config As Long
Dim j As Long
Dim i As Long

Set Wk = ActiveWorkbook

lastrow_Header_Config = Wk.Sheets("Config").Cells(Rows.Count, "W").End(xlUp).Row
ReDim HeaderArray(Application.WorksheetFunction.CountA(Wk.Sheets("Config").Range("W2:W" & lastrow_Header_Config))-1) As Variant
j = 0

For i = 2 To lastrow_Header_Config
    HeaderValue = Wk.Sheets("Config").Range("W" & i).Value
    If HeaderValue <> "" Then
        HeaderArray(j) = HeaderValue
        j = j + 1
    End If
Next

End Sub

試試看,看看它如何為您工作

密切注意ReDim HeaderArray(j)行和ReDim Preserve HeaderArray(j)

Sub Trial()
    Dim HeaderArray() As Variant
    Dim HeaderValue As String
    Dim j As Long
    Dim i As Long
        Set Wk = ActiveWorkbook
        lastrow_header_Config = Wk.Sheets("Config").Cells(Rows.Count, "W").End(xlUp).Row
        j = 1
        ReDim HeaderArray(j)   '<============= initialize your array length
        For i = 2 To lastrow_header_Config
            HeaderValue = Wk.Sheets("Config").Range("W" & i).Value
            If HeaderValue <> "" Then
                ReDim Preserve HeaderArray(j) '<================= adjust your array length to accomodate the additional info
                HeaderArray(j - 1) = HeaderValue '// Subscript out of range error
                j = j + 1
            End If
        Next
End Sub

另外,您可能想使用option關鍵字繼續閱讀。 默認情況下,數組的第一個數據點的索引為0,因此例如array(1)創建的數組具有1個數據點,但是要引用該數據點,則可以使用array(0)。 如果您希望使用array(1)引用數組中的第一個數據點,則可以在模塊的頂部使用Option Base 1關鍵字。

在第一遍, j = 1 因此,您嘗試將HeaderArray(0)設置為一個值,而HeaderArray可能基於1。
您最終可以使用Option Base 0或顯式使用Redim HeaderArray(0 to 10) (或所需的任何值)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM