I am trying to loop through a ledger of transactions and tag costs that correlate to certain account codes. For example, account code 123 would be tagged as a 'Hardware/Software' cost. I first produced code that combed through the ledger via reading each cell (a very lazy solution). This process took ~12-17 minutes to tag all costs in the ledger. I'm now trying to implement an array solution to tag all costs by reading the account codes through one array and then tag the costs in another array if it meets the requirements of an If/Then Statement.
The code below is looping through account codes and tagging 'misc' costs, 'hardware' costs, and 'not expense' costs.
How can I make the code work so that I can go through a series of If/Then statements with the account code to specify the tagging based on what the account code is? I keep getting an error ("array subscript out of range") when I try to assign the 'Not Expense' tag in the second If/Then statement in the code below:
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
I expect the output to tag all costs with account code '716' as 'misc' and 'HW/SW', and tag costs with account code '182', '160', '250', '258', '180' as 'Not Expense'
I hope this code helps as it is a small part of the overall code that combs through a bunch of other account codes.
arTesting = rng.Value. This will yield a 2-dimensional array (even for a single column, in which case the second index is always 1) but this is much faster than 1500 +ReDim Preserves(especially because theReDim Preserveisn't required in this case since you could justDimthe array once before you start).If arTesting(i) = 182 Or 160 Or 250 Or 258 Or 180doesn't mean what you think it means. That isn't shorthand forIf arTesting(i) = 182 Or arTesting(i) =160 Or arTesting(i) =250 Or arTesting(i) =258 Or arTesting(i) =180(which is what I suspect you meant).If arTesting(i) = 182 Or 160 Or 250 Or 258 Or 180isn't the same asIf arTesting(i) = 182 Or arTesting(i) =160etc. Your solution worked great - thanks so much for your help!