打印来自 For Each 函数 VBA 的数组结果得到下标超出范围错误

Posted

技术标签:

【中文标题】打印来自 For Each 函数 VBA 的数组结果得到下标超出范围错误【英文标题】:Print Array result from For Each function VBA getting subscript out of range error 【发布时间】:2020-08-12 21:42:44 【问题描述】:

我不断收到下面的下标超出范围错误,我不明白为什么。我不是 VBA 大师,我知道如何使用 JS 来做到这一点,但是当我必须时,我会通过项目实现 VBA。在这种情况下,我需要为每个语句创建一个数组并将其打印到文件中。我只是省略了数组并从 for each 循环中打印(这有效),但我需要能够添加到文件的内容中,然后还可以稍后从不同的函数访问数组(另一个问题)。

希望有人可以帮助解决我在这里做错的事情。

Public Function Orders()
    Dim ItemDescription As String, Counter As Integer, Range As Range, sArray() As Variant
    ReDim sArray(1 To 1) As Variant
    length = Cells(Rows.Count, 1).End(xlUp).Row
    Set Range = ActiveSheet.Range("A2:A" & length)
    IntFile = FreeFile
    StrFile = "C:\Projects\Test.txt"
    Open StrFile For Output As #IntFile
    For Each Cell In Range
        ItemDescription = Cell.Offset(0, 19).Value
            If (Cell.Value = Cell.Offset(1, 0).Value And Cell.Value <> Cell.Offset(-1, 0).Value) Or (Cell.Value <> Cell.Offset(-1, 0).Value And Cell.Value <> Cell.Offset(1, 0).Value) Then
                Counter = 1
            ElseIf (Cell.Value = Cell.Offset(1, 0).Value And Cell.Value = Cell.Offset(-1, 0).Value) Or (Cell.Value <> Cell.Offset(1, 0).Value And Cell.Value = Cell.Offset(-1, 0).Value) Then
                Counter = Counter + 1
            End If
            If Counter = 1 Then
                OlStr = ItemDescription
            ElseIf Counter > 1 Then
                 OlStr = ItemDescription & " " & "your count =" & " " & Counter
            End If
            sArray(UBound(sArray)) = OlStr
            ReDim Preserve sArray(1 To UBound(sArray) + 1) As Variant
    Next Cell
    Print #IntFile, sArray(1, UBound(sArray))
    Close #IntFile
End Function

问题出现在“Print #IntFile, sArray(1, UBound(sArray))”行,倒数第三行。我知道这意味着我试图引用数组维度之外的项目,但我似乎无法弄清楚为什么。如果我将 Print 行放在 For Each 中,我仍然会收到错误消息。这是错误:

请注意,看起来 UBound 已正确创建。我的工作表中有 2537 行,尽管它确实有一个标题。

非常感谢任何帮助!!!

【问题讨论】:

你有一个一维数组,所以你只能指定一个索引值。 sArray(1)sArray(UBound(sArray)) 是价值,但不是 sArray(1, UBound(sArray)) 如果您只想打印所有单元格值,您可以将Print #IntFile, sArray(UBound(sArray)) 放在 Redim 语句之前的 For Each 循环中。或者,您可以绕过数组并执行Print #IntFile, OlStr @DecimalTurn 我能够毫无问题地执行 #IntFile、OlStr,看起来我也可以在 for each 循环中打印数组(感谢 1D v 2D 数组课程)。部分原因是我需要能够存储数组以供以后使用。在 JS 中,我只会在函数中返回它,然后稍后将函数作为变量调用。我以为我可以在 VBA 中做同样的事情,但是将函数声明为 String、Variant 或其他任何内容,然后尝试将其存储为变量并稍后调用似乎不起作用。 是的,变量和数组的范围在 JS 和 VBA 中是完全不同的。如果你想跨过程重用一个数组,你总是可以将它声明为公共的。如果您想对此有正确的答案,请随时提出单独的问题。 【参考方案1】:

根据我的cmets:

您有一个一维数组,因此您只能指定一个索引值。 sArray(1)sArray(UBound(sArray)) 有效,但 sArray(1, UBound(sArray)) 无效

如果您只想打印所有单元格值,您可以将Print #IntFile, sArray(UBound(sArray)) 放在 Redim 语句之前的 For Each 循环中。或者,您可以绕过数组并执行Print #IntFile, OlStr

【讨论】:

以上是关于打印来自 For Each 函数 VBA 的数组结果得到下标超出范围错误的主要内容,如果未能解决你的问题,请参考以下文章

在 msxsl 中将节点作为参数传递:来自 XSLT for-each 的脚本 javascript 函数不起作用

如何循环 JSON 数据以获取所有对象的打印百分比值,使用 for each 或 other [重复]

for each语句

for Each篇

使用ajax jQuery for-each函数在表中追加多个数据

使用 for-each 循环打印 ArrayList