将变量分配给数组时,为什么出现数组下标超出范围错误?

时间:2019-04-03 14:36:46

标签: arrays vba loops tagging

我正在尝试遍历交易分类帐和标记与某些帐户代码相关的成本。例如,帐户代码123将被标记为“硬件/软件”成本。我首先生成了代码,这些代码通过读取每个单元格(非常懒惰的解决方案)在分类帐中进行了梳理。这个过程花费了大约12-17分钟的时间来标记分类帐中的所有成本。我现在正在尝试实现一种数组解决方案,以通过读取一个数组中的帐户代码来标记所有成本,然后在满足If / Then语句要求的情况下,在另一个数组中标记成本。

下面的代码遍历帐户代码,并标记“杂项”成本,“硬件”成本和“非费用”成本。

如何使代码正常工作,以便我可以通过一系列带有帐户代码的If / Then语句根据帐户代码是什么来指定标记?尝试在下面的代码的第二个If / Then语句中分配“ Not Expense”标签时,我不断收到错误消息(“数组下标超出范围”)

Sub arrayTest()
Dim arTesting() As Variant
Dim arTag1(1 To 1550) As Variant 'this is just a test range
Dim arTag2(1 To 1550) As Variant 'this is just a test range
Dim rng, cell As Range
Dim HWSWTag, miscTag, notExpenseTag As String
Dim x As Integer
Set rng = Range("G2:G1551")

miscTag = "Misc"
HWSWTag = "HW/SW"
notExpenseTag = "Not Expense"

x = 1
'Read in the range of account codes
For Each cell In rng
    ReDim Preserve arTesting(x)
    arTesting(x) = cell.Value
    x = x + 1
    Next cell

'Now tag the costs to arTag1 and arTag2    
Dim i As Long
i = 1
For i = LBound(arTesting) To UBound(arTesting)
    If arTesting(i) = 716 Then
                arTag1(i) = miscTag
                arTag2(i) = HWSWTag
    End If

    If arTesting(i) = 182 Or 160 Or 250 Or 258 Or 180 Then
        arTag1(i) = notExpenseTag 'This is where I get the error 
    End If

'Debug.Print arTesting(i)

Next i

'Now paste the tags into the worksheet

Range("AL2:AL1551").Value = WorksheetFunction.Transpose(arTag1)
Range("AM2:AM1551").Value = WorksheetFunction.Transpose(arTag2)

End Sub

我希望输出将帐户代码为“ 716”的所有成本标记为“ misc”和“ HW / SW”,并标记帐户代码为“ 182”,“ 160”,“ 250”,“ 258”, “ 180”为“非费用”

我希望这段代码能对您有所帮助,因为它只是整个代码的一小部分,可以梳理出许多其他帐户代码。

1 个答案:

答案 0 :(得分:1)

以下内容应该可以完成您似乎想做的事情。它进行了一些更改:

  1. 它正确声明了3个字符串变量,而不是2个变量和1个字符串
  2. 它读取1行代码中的值
  3. 它使用Select Case而不是If语句,但条件并不意味着您可能要做什么。 x = 1 Or 2 Or 3的意思是(x = 1) Or 2 Or 3(这几乎永远不是您想要的),而不是预期的x = 1 Or x = 2 Or x = 3

代码如下:

Sub arrayTest()
    Dim arTesting() As Variant
    Dim arTag1(1 To 1550, 1 To 1) As Variant 'this is just a test range
    Dim arTag2(1 To 1550, 1 To 1) As Variant 'this is just a test range
    Dim rng As Range, cell As Range
    Dim HWSWTag As String, miscTag As String, notExpenseTag As String
    Dim i As Long

    Set rng = Range("G2:G1551")

    miscTag = "Misc"
    HWSWTag = "HW/SW"
    notExpenseTag = "Not Expense"

    arTesting = rng.Value

    For i = LBound(arTesting,1) To UBound(arTesting,1)
        Select Case arTesting(i,1)
            Case 716:
                arTag1(i, 1) = miscTag
                arTag2(i, 1) = HWSWTag
            Case 182, 160, 250, 258, 180:
                arTag1(i, 1) = notExpenseTag
        End Select
    Next i

    Range("AL2:AL1551").Value = arTag1
    Range("AM2:AM1551").Value = arTag2
End Sub