I have some code that looks like this:
pos.Clutch = sh2.Cells(R, Clutch)
pos.Wiper = sh2.Cells(R, Wiper)
pos.Alternator = sh2.Cells(R, Alternator)
pos.Compressor = sh2.Cells(R, Compressor)
...
pos.Telephone = sh2.Cells(R, Telephone)
poss.Add pos
poss is a collection, and Clutch, Wiper etc. are column indexes (starting from 1). This currently works but is very ugly. I'm looking for a way to do something like this...
Do While i <= classProperty.count
For each classProperty in pos
classProperty = sh2.Cells(R + 1, i)
Next classProperty
Loop
Obviously that wouldn't work but does anyone have any advice on how to make a method or collection within a class that would accomplish roughly the same?
Might be able to use some code like this. As is this prints off every procedure and property thought:
Good luck, LC
VBA classes don't allow to define a constructor.
In the main module I would create a "creator":
In the class:
As others have stated there is no direct way to loop through an object properties. I have a spreadsheet which stores many values which I need to read in at run time, similar to yours. The best method I have found to do this is by using the
CallByName
method which allows you set or get a property by name.Now, some might say the initial set up is overkill, but I frequently add and remove these properties so doing likewise with code is even more hassle. So the beauty of this method is you can frequently modify your number of properties without having to change this code. You can use the awesome functions that make use of
CallByName
from here: https://stackoverflow.com/a/5707956/1733206Then for your example, I would do the following in my
poss
collection (note this doesn't do any error checking etc which you may like to do):Here is an example in a workbook: https://dl.dropboxusercontent.com/u/13173101/VBAObject.xlsm
Edit: Since you will be changing the object often, I've included another module which is really handy and will actually write the
pos
class for you based on the column headings in your worksheet. That means if you add another column it will add those properties to the object! It assumes that all properties are strings but you can modify to suit.I don't know of a good way. The only reason it's ugly is because you haven't hidden it in a class yet. Take this procedure
Nothing ugly about that. Now the AddFromRange method is a little ugly, but you only have to look at that when you write it or when you're data changes.
Update: Alternative method for eating an array instead of a Range.