问题
Apologies for what is no doubt a simple question - am very new to coding so even finding the answer from existing information is tough.
Anyway...
I've defined a Class with 4 value (1 x Single, 1 x String (to use as key), and 2 x Range)
I've then managed to set the Collection based on the class and populate the collection, and can use Debug.Print to print the entire collection's values and also to count the number of items in the collection.
But I can't access a single object from the collection, either by using index position or the specified Key.
When trying I get
Runtime error 438 - Object doesn't support this property or method.
The underlying spreadsheet is a 4 column, 200 row sheet, and the eventual goal is for each row to be an object, and then populate a given location for an object (row) with a variable defined in a separate set of code.
Anyway, the Class (PriceLadder) code is:
Public ladderPriceKey As String
Public ladderPrice As Single
Public layMatchedLocation As Range
Public backMatchedLocation As Range
and then the module code is:
Sub initialiseLadder()
'initialise ladder as collection
Dim ladder As Collection
Set ladder = New Collection
Dim cell As Range
Dim price As PriceLadder
'for each cell in Column A
For Each cell In Sheets(2).Range("A11:A220") ' & Range("A" & Rows.Count).End(xlUp).Row)
' create a new priceladder object
Set price = New PriceLadder
' fill the data
price.ladderPrice = cell
price.ladderPriceKey = cell
Set price.layMatchedLocation = Range(cell.Offset(0, 2).Address(RowAbsolute:=True, ColumnAbsolute:=True))
Set price.backMatchedLocation = Range(cell.Offset(0, 3).Address(RowAbsolute:=True, ColumnAbsolute:=True))
' add the price to the collection of ladder prices
ladder.Add price, price.ladderPriceKey 'price.ladderPriceKey set as the key for the collection object
Next
Debug.Print ladder.Count
Debug.Print ladder("10")
' Dim p As PriceLadder
'For Each p In ladder
'Debug.Print "PriceKey: " & p.ladderPriceKey & vbTab & "BackLocation: " & p.backMatchedLocation.Address & vbTab & "LayLocation: " & p.layMatchedLocation.Address & vbTab & "Price: " & p.ladderPrice()
' Next
End Sub
The line that produces the error is:
Debug.Print ladder("10")
where "10" is one of the values added as a key from price.ladderKeyPrice
Really sorry if this is a horrible newbie type question.
Thanks for any help than can be given.
Richard
来源:https://stackoverflow.com/questions/49281583/cant-access-object-from-collection