0

Could anyone please explain what is the reason for this error? The code looks totally fine to me.

Public n As Long, i As Long, prodCode As String
Private Sub newArray()

    n = wsProducts.Range("A1", wsProducts.Range("A1").End(xlDown)).Rows.Count

    ReDim prodCode(n)

    For i = 1 To n
        prodCode(i) = wsProducts.Range("A1").Offset(i, 0)
    Next i

End Sub
4
  • 6
    You have declared prodCode as a string, but not an array of strings Commented Feb 16, 2017 at 18:53
  • 2
    prodCode() As String Commented Feb 16, 2017 at 18:54
  • @YowE3K thank you! That was so easy! Commented Feb 16, 2017 at 18:58
  • 2
    BTW - If you declare prodCode() As Variant (or, in this case, even as prodCode As Variant) you can then get rid of the ReDim statement by replacing the loop with prodCode = Application.Transpose(wsProducts.Range("A1:A" & n)) Commented Feb 16, 2017 at 18:59

1 Answer 1

2

You have declared prodCode as a string, but not as an array of strings.

You need to use prodCode() As String if you wish to use that variable as an array.


Note: You can also speed your code up by using a Variant array, which allows you then to "load" the array in one transfer operation:

Public n As Long, prodCode() As Variant
Private Sub newArray()

    n = wsProducts.Range("A1", wsProducts.Range("A1").End(xlDown)).Rows.Count
    'P.S. That statement would simplify to 
    'n = wsProducts.Range("A1").End(xlDown).Row

    prodCode = Application.Transpose(wsProducts.Range("A1:A" & n)

End Sub

Application.Transpose has been used to change the shape of the array from being a 1 To n, 1 To 1 two-dimensional array to being a 1 To n one-dimensional array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.