vba 在字符串数组中填充数据时下标超出范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18697210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:13:36  来源:igfitidea点击:

Subscript out of range when filling data in string array

vbamultidimensional-array

提问by Kris Van den Bergh

I'm trying to store some reference data in a string array and then use that later on to compare with another string array. However, the code is not working since I'm getting a "subscript out of range" error (see code comment below).

我正在尝试将一些参考数据存储在一个字符串数组中,然后稍后使用它与另一个字符串数组进行比较。但是,代码不起作用,因为我收到“下标超出范围”错误(请参阅下面的代码注释)。

Sub StoreBaseReferences()
    Dim cell As Range
    Dim val As Variant
    Dim stringValues() As String
    Dim i, rowCounter, columnCounter As Integer

    rowCounter = 0
    columnCounter = 0
    For i = 2 To Sheets("sheet").UsedRange.rows.Count

        For Each cell In Range(Cells(i, 2), Cells(i, 4))
            stringValues(rowCounter, columnCounter) = cell.Value 'this is throwing the subscript ouf of range error
            columnCounter = columnCounter + 1
        Next cell

        rowCounter = rowCounter + 1
        columnCounter = 0
    Next i
    MsgBox (stringValues(0, 0))


End Sub

What is missing here?

这里缺少什么?

回答by

you are declaring a 1d array Dim stringValues() As String

您正在声明一个一维数组 Dim stringValues() As String

but trying to use it as a 2d array stringValues(rowCounter, columnCounter)

但试图将其用作二维数组 stringValues(rowCounter, columnCounter)

Also, you are not declaring the size of the array and you are trying to use it. In VBA you have to make sure you tell the size of the array at the declaration time.

此外,您没有声明数组的大小,而是尝试使用它。在 VBA 中,您必须确保在声明时告知数组的大小。

To delcare the count of elements that the array is capable of storing

delcare 数组能够存储的元素数

Dim stringArray(0 to 10)or Dim stringArray(10)

Dim stringArray(0 to 10)或者 Dim stringArray(10)

and when iterating the counter starts at 0.

当迭代计数器时,从0.

Using ReDim stringValues()allows you to resize the bounds at a later stage.

使用ReDim stringValues()允许您在稍后阶段调整边界大小。

The topic is too broad to go over in one answer so check out the links to learn out how to dimension your array

该主题太广泛,无法在一个答案中详细介绍,因此请查看链接以了解如何确定数组的维度

回答by Joe

Arrays in VBA need to be dimensioned with the number of elements that are expected to be used. You've defined the dimension, but not specified how many elements will be added to it. Try adding the following line just before the For loop:

VBA 中的数组需要使用预期使用的元素数量进行标注。您已定义维度,但未指定将添加多少元素。尝试在 For 循环之前添加以下行:

ReDim stringValues(Sheets("sheet").UsedRange.Rows.Count, 3)