Munkeeface
Munkeeface

Reputation: 409

Why am I getting a "Subscript is out of range" error?

I have the following code that is within a UserForm, called near the end of a bunch of other processes in the main module, but when it reaches Me.GPListBox.List(iterI, 0) = Split (CCGPValues(key), " - ")(0) I get an error stating the subscript is out of range.

In the Debug.Print directly before the For Each, the console outputs "Jorge Cardona". This is the first piece of the split. CCGPValues(key) equals "Jorge Cardona - $207.31", but when it calls the same split within the GPListBox, it breaks. Why is this happening when it works via Debug.print?

    Dim key As Variant, iterI As Integer, iterX As Integer
    Debug.Print Split(CCGPValues(147), " - ")(0)
    For Each key1 In CCGPValues.Keys
            Me.GPListBox.AddItem
            Me.GPListBox.List(iterI, 0) = Split(CCGPValues(key), " - ")(0) 'Breaks here
            Me.GPListBox.List(iterI, 1) = Split(CCGPValues(key), " - ")(1)
            CCGPValuesCount = CCGPValuesCount + 1
            iterI = iterI + 1
    Next key1

Upvotes: 1

Views: 114

Answers (1)

cyboashu
cyboashu

Reputation: 10433

You are running loop on Key1 in For Each key1 In CCGPValues.Keys and for the split part you are passing key in = Split(CCGPValues(key), " - ")(0)

So there is nothing to split and hence the resulting array is not initialized. Then from a blank array, you are trying to read first element. So the sub script error.

Option Explicit avoids these kind of headaches.

Upvotes: 7

Related Questions