Archive for the 'Programming' Category

Latex bibentry package and IEEE bibliography style, from Night Walker

June 4, 2012

From here:  http://nw360.blogspot.co.uk/2012/05/latex-bibentry-package-and-ieee.html

 

When I used Latex bibentry package together with IEEEtran bibliography style, an error would occur:
paragraph ended before \BR@bibitem was complete.

Googled but didn’t find any solution until came to this page. The solution is to use the IEEEtrantools LaTeX package.

To use the package, load it using

\usepackage[retainorgcmds]{IEEEtrantools}

The option [retainorgcmds] asks IEEEtrantools NOT to override the standard LaTeX itemize, enumerate and description list environments.

Of course you need to load bibentry
\usepackage{bibentry}

Add the following entry to the .bib file:

@ieeetranbstctl{BSTcontrol,
CTLdash_repeated_names = {no},
CTLuse_alt_spacing = {no}}

This entry is to give you the access to the IEEEtran.bst controls. CTLdash_repeated_namescontrols whether dashes are used for repeated names or not. CTLuse_alt_spacing controls the alternate interword spacing for bib entries with URLs. The label of the entry “BSTcontrol” can be changed as long as you use the same name in the \bstctlcite{} command.

After the \begin{document} command, add

\bstctlcite{BSTcontrol} % activate the IEEEtran controls.
\nobibliography*
\bibliographystyle{ieeetran}

Now the bibentry works well with IEEEtran style.

References:
http://www.mail-archive.com/lyx-users@lists.lyx.org/msg70594.html
http://www.michaelshell.org/tex/ieeetran/tools/

Click to access IEEEtran_bst_HOWTO.pdf

 

 

Teach Yourself Programming in Ten Years

July 31, 2011

Peter Norvig

Why is everyone in such a rush?

Walk into any bookstore, and you’ll see how to Teach Yourself Java in 7 Days alongside endless variations offering to teach Visual Basic, Windows, the Internet, and so on in a few days or hours. I did the following power search at Amazon.com:

     pubdate: after 1992 and title: days and
      (title: learn or title: teach yourself)

and got back 248 hits. The first 78 were computer books (number 79 was Learn Bengali in 30 days). I replaced “days” with “hours” and got remarkably similar results: 253 more books, with 77 computer books followed by Teach Yourself Grammar and Style in 24 Hoursat number 78. Out of the top 200 total, 96% were computer books.

The conclusion is that either people are in a big rush to learn about computers, or that computers are somehow fabulously easier to learn than anything else. There are no books on how to learn Beethoven, or Quantum Physics, or even Dog Grooming in a few days. Felleisen et al. give a nod to this trend in their book How to Design Programs, when they say “Bad programming is easy. Idiots can learn it in 21 days, even if they are dummies.

Let’s analyze what a title like Learn C++ in Three Days could mean:

  • Learn: In 3 days you won’t have time to write several significant programs, and learn from your successes and failures with them. You won’t have time to work with an experienced programmer and understand what it is like to live in a C++ environment. In short, you won’t have time to learn much. So the book can only be talking about a superficial familiarity, not a deep understanding. As Alexander Pope said, a little learning is a dangerous thing.
  • C++: In 3 days you might be able to learn some of the syntax of C++ (if you already know another language), but you couldn’t learn much about how to use the language. In short, if you were, say, a Basic programmer, you could learn to write programs in the style of Basic using C++ syntax, but you couldn’t learn what C++ is actually good (and bad) for. So what’s the point? Alan Perlis once said: “A language that doesn’t affect the way you think about programming, is not worth knowing”. One possible point is that you have to learn a tiny bit of C++ (or more likely, something like JavaScript or Flash’s Flex) because you need to interface with an existing tool to accomplish a specific task. But then you’re not learning how to program; you’re learning to accomplish that task.
  • in Three Days: Unfortunately, this is not enough, as the next section shows.

Teach Yourself Programming in Ten Years

Researchers (Bloom (1985), Bryan & Harter (1899), Hayes (1989), Simmon & Chase (1973)) have shown it takes about ten years to develop expertise in any of a wide variety of areas, including chess playing, music composition, telegraph operation, painting, piano playing, swimming, tennis, and research in neuropsychology and topology. The key is deliberative practice: not just doing it again and again, but challenging yourself with a task that is just beyond your current ability, trying it, analyzing your performance while and after doing it, and correcting any mistakes. Then repeat. And repeat again. There appear to be no real shortcuts: even Mozart, who was a musical prodigy at age 4, took 13 more years before he began to produce world-class music. In another genre, the Beatles seemed to burst onto the scene with a string of #1 hits and an appearance on the Ed Sullivan show in 1964. But they had been playing small clubs in Liverpool and Hamburg since 1957, and while they had mass appeal early on, their first great critical success, Sgt. Peppers, was released in 1967. Malcolm Gladwellreports that a study of students at the Berlin Academy of Music compared the top, middle, and bottom third of the class and asked them how much they had practiced:

Everyone, from all three groups, started playing at roughly the same time – around the age of five. In those first few years, everyone practised roughly the same amount – about two or three hours a week. But around the age of eight real differences started to emerge. The students who would end up as the best in their class began to practise more than everyone else: six hours a week by age nine, eight by age 12, 16 a week by age 14, and up and up, until by the age of 20 they were practising well over 30 hours a week. By the age of 20, the elite performers had all totalled 10,000 hours of practice over the course of their lives. The merely good students had totalled, by contrast, 8,000 hours, and the future music teachers just over 4,000 hours.

So it may be that 10,000 hours, not 10 years, is the magic number. (Henri Cartier-Bresson (1908-2004) said “Your first 10,000 photographs are your worst,” but he shot more than one an hour.) Samuel Johnson (1709-1784) thought it took even longer: “Excellence in any department can be attained only by the labor of a lifetime; it is not to be purchased at a lesser price.” And Chaucer (1340-1400) complained “the lyf so short, the craft so long to lerne.” Hippocrates (c. 400BC) is known for the excerpt “ars longa, vita brevis”, which is part of the longer quotation “Ars longa, vita brevis, occasio praeceps, experimentum periculosum, iudicium difficile”, which in English renders as “Life is short, [the] craft long, opportunity fleeting, experiment treacherous, judgment difficult.” Although in Latin, ars can mean either art or craft, in the original Greek the word “techne” can only mean “skill”, not “art”.

Here’s my recipe for programming success:

  • Get interested in programming, and do some because it is fun. Make sure that it keeps being enough fun so that you will be willing to put in ten years.
  • Talk to other programmers; read other programs. This is more important than any book or training course.
  • Program. The best kind of learning is learning by doing. To put it more technically, “the maximal level of performance for individuals in a given domain is not attained automatically as a function of extended experience, but the level of performance can be increased even by highly experienced individuals as a result of deliberate efforts to improve.” (p. 366) and “the most effective learning requires a well-defined task with an appropriate difficulty level for the particular individual, informative feedback, and opportunities for repetition and corrections of errors.” (p. 20-21) The book Cognition in Practice: Mind, Mathematics, and Culture in Everyday Life is an interesting reference for this viewpoint.
  • If you want, put in four years at a college (or more at a graduate school). This will give you access to some jobs that require credentials, and it will give you a deeper understanding of the field, but if you don’t enjoy school, you can (with some dedication) get similar experience on the job. In any case, book learning alone won’t be enough. “Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter” says Eric Raymond, author of The New Hacker’s Dictionary. One of the best programmers I ever hired had only a High School degree; he’s produced a lot of great software, has his own news group, and made enough in stock options to buy his own nightclub.
  • Work on projects with other programmers. Be the best programmer on some projects; be the worst on some others. When you’re the best, you get to test your abilities to lead a project, and to inspire others with your vision. When you’re the worst, you learn what the masters do, and you learn what they don’t like to do (because they make you do it for them).
  • Work on projects after other programmers. Be involved in understanding a program written by someone else. See what it takes to understand and fix it when the original programmers are not around. Think about how to design your programs to make it easier for those who will maintain it after you.
  • Learn at least a half dozen programming languages. Include one language that supports class abstractions (like Java or C++), one that supports functional abstraction (like Lisp or ML), one that supports syntactic abstraction (like Lisp), one that supports declarative specifications (like Prolog or C++ templates), one that supports coroutines (like Icon or Scheme), and one that supports parallelism (like Sisal).
  • Remember that there is a “computer” in “computer science”. Know how long it takes your computer to execute an instruction, fetch a word from memory (with and without a cache miss), read consecutive words from disk, and seek to a new location on disk. (Answers here.)
  • Get involved in a language standardization effort. It could be the ANSI C++ committee, or it could be deciding if your local coding style will have 2 or 4 space indentation levels. Either way, you learn about what other people like in a language, how deeply they feel so, and perhaps even a little about why they feel so.
  • Have the good sense to get off the language standardization effort as quickly as possible.

With all that in mind, its questionable how far you can get just by book learning. Before my first child was born, I read all the How Tobooks, and still felt like a clueless novice. 30 Months later, when my second child was due, did I go back to the books for a refresher? No. Instead, I relied on my personal experience, which turned out to be far more useful and reassuring to me than the thousands of pages written by experts.

Fred Brooks, in his essay No Silver Bullet identified a three-part plan for finding great software designers:

  1. Systematically identify top designers as early as possible.
  2. Assign a career mentor to be responsible for the development of the prospect and carefully keep a career file.
  3. Provide opportunities for growing designers to interact and stimulate each other.

This assumes that some people already have the qualities necessary for being a great designer; the job is to properly coax them along. Alan Perlisput it more succinctly: “Everyone can be taught to sculpt: Michelangelo would have had to be taught how not to. So it is with the great programmers”.

So go ahead and buy that Java book; you’ll probably get some use out of it. But you won’t change your life, or your real overall expertise as a programmer in 24 hours, days, or even months.


References

Bloom, Benjamin (ed.) Developing Talent in Young People, Ballantine, 1985.

Brooks, Fred, No Silver Bullets, IEEE Computer, vol. 20, no. 4, 1987, p. 10-19.

Bryan, W.L. & Harter, N. “Studies on the telegraphic language: The acquisition of a hierarchy of habits. Psychology Review, 1899, 8, 345-375

Hayes, John R., Complete Problem Solver Lawrence Erlbaum, 1989.

Chase, William G. & Simon, Herbert A. “Perception in Chess” Cognitive Psychology, 1973, 4, 55-81.

Lave, Jean, Cognition in Practice: Mind, Mathematics, and Culture in Everyday Life, Cambridge University Press, 1988.


Answers

Approximate timing for various operations on a typical PC:

execute typical instruction 1/1,000,000,000 sec = 1 nanosec
fetch from L1 cache memory 0.5 nanosec
branch misprediction 5 nanosec
fetch from L2 cache memory 7 nanosec
Mutex lock/unlock 25 nanosec
fetch from main memory 100 nanosec
send 2K bytes over 1Gbps network 20,000 nanosec
read 1MB sequentially from memory 250,000 nanosec
fetch from new disk location (seek) 8,000,000 nanosec
read 1MB sequentially from disk 20,000,000 nanosec
send packet US to Europe and back 150 milliseconds = 150,000,000 nanosec

Appendix: Language Choice

Several people have asked what programming language they should learn first. There is no one answer, but consider these points:

  • Use your friends. When asked “what operating system should I use, Windows, Unix, or Mac?”, my answer is usually: “use whatever your friends use.” The advantage you get from learning from your friends will offset any intrinsic difference between OS, or between programming languages. Also consider your future friends: the community of programmers that you will be a part of if you continue. Does your chosen language have a large growing community or a small dying one? Are there books, web sites, and online forums to get answers from? Do you like the people in those forums?
  • Keep it simple. Programming languages such as C++ and Java are designed for professional development by large teams of experienced programmers who are concerned about the run-time efficiency of their code. As a result, these languages have complicated parts designed for these circumstances. You’re concerned with learning to program. You don’t need that complication. You want a language that was designed to be easy to learn and remember by a single new programmer.
  • Play. Which way would you rather learn to play the piano: the normal, interactive way, in which you hear each note as soon as you hit a key, or “batch” mode, in which you only hear the notes after you finish a whole song? Clearly, interactive mode makes learning easier for the piano, and also for programming. Insist on a language with an interactive mode and use it.

Given these criteria, my recommendations for a first programming language would be Python or Scheme. But your circumstances may vary, and there are other good choices. If your age is a single-digit, you might prefer Alice or Squeak (older learners might also enjoy these). The important thing is that you choose and get started.


Appendix: Books and Other Resources

Several people have asked what books and web pages they should learn from. I repeat that “book learning alone won’t be enough” but I can recommend the following:


Notes

T. Capey points out that the Complete Problem Solver page on Amazon now has the “Teach Yourself Bengali in 21 days” and “Teach Yourself Grammar and Style” books under the “Customers who shopped for this item also shopped for these items” section. I guess that a large portion of the people who look at that book are coming from this page. Thanks to Ross Cohen for help with Hippocrates.

How to use NetBeans IDE with an English User Interface

July 22, 2011

The trick is install again with one argument, –locale en:US

Example:

start – run – cmd –
netbeans-7.0beta-ml-windows –locale en:US
NETBEANS-6.9.1-ML-WINDOWS –locale en:US

This trick works also under linux

chmod +x
./netbeans_version –locale en:US

(not sure this one works)

———————-

1. Temporary Solution

Add “–locale en:US” at the end of Netbeans startup command.

“C:\\Program Files\\NetBeans 6.0.1\\bin\\netbeans.exe”  –locale en:US

2. Permanent Solution

Go to Netbeans installation directory, for example,

C:\\Program Files\\NetBeans 6.0.1\\etc

Open “netbeans.conf” and find netbeans default option line

netbeans_default_options=”-J-client -J-Xss2m -J-Xms32m -J-XX:PermSize=32m -J-XX:MaxPermSize=200m -J-Xverify:none -J-Dapple.laf.useScreenMenuBar=true”

Add “-J-Duser.language=en -J-Duser.region=US” to the end of this line

netbeans_default_options=”-J-client -J-Xss2m -J-Xms32m -J-XX:PermSize=32m -J-XX:MaxPermSize=200m -J-Xverify:none -J-Dapple.laf.useScreenMenuBar=true -J-Duser.language=en -J-Duser.region=US

http://wiki.netbeans.org/FaqMessagesInEnglish

http://blogs.oracle.com/tao/entry/set_netbeans_user_interface_language

http://nw360.blogspot.com/2008/11/change-netbeans-ide-interface-language.html

(this one worked fine.)

————————–

Of course, you can change your system locale to English but it isn’t ideal as it may affect other programs that depend on the system locale settings. What I suggest is that you set the “–locale” start-up option to English when you run Netbeans.

For example, you can open a command prompt window, change to the bin folder that is under your netbeans installation folder (e.g. C:\Program Files\NetBeans 6.5.1\bin) and start the Netbeans IDE by typing the ff:

netbeans –locale en

Alternatively, you can specify this start-up option in the netbeans.conf file that is located in the etc folder under your NetBeans installation folder (e.g. C:\Program Files\NetBeans 6.5.1\etc\netbeans.conf). To do this, open the file in a text editor and change the value for the option “netbeans_default_options” by inserting “–locale en”.

For example, this is what the line looks like before I inserted the option:

netbeans_default_options=”-J-client -J-Xverify:none -J-Xss2m …

This is the line after I changed it:

netbeans_default_options=”–locale en -J-client -J-Xverify:none -J-Xss2m …

Once you’ve modified netbeans.conf, you can start Netbeans as you would normally do and you will get all UI elements in English.

http://misteratmisis.com/infotech/how-use-netbeans-ide-english-user-interface-japanese-environment

(not tried, should be fine.)

VBA: store an array in class

March 1, 2011

In a module put this code

Sub test()

Set ArrayClass = New Class1

For i = ArrayClass.lower To ArrayClass.upper
ArrayClass.WriteArray i, i
Next i

For i = ArrayClass.lower To ArrayClass.upper
msgbox(ArrayClass.ReadArray(i))
Next i

End Sub

Insert a Class module. the first one will be Class1 which is in the above
sub in the New statement. Must be the same

Insert this code into class1module

Dim MyArray As Variant
Public lower As Long
Public upper As Long

Private Sub Class_Initialize()
ReDim MyArray(100)

lower = LBound(MyArray)
upper = UBound(MyArray)
End Sub
Public Sub WriteArray(i, a)

MyArray(i) = a

End Sub
Public Function ReadArray(i)

ReadArray = MyArray(i)

End Function

VBA, Excel, Type or Class?

March 1, 2011

http://excelicious.wordpress.com/2009/03/20/type-or-class/#comment-355

http://www.cpearson.com/Excel/Classes.aspx

Type or Class?

i

1 Votes

Quantcast

I’ve been kept quite busy recently building an application for work. It’s a fairly standard task – take a number of regularly (monthly) populated workbooks from offices around the country and consolidate the data in them at a regional and national level. Aside from a little fluffing around with validation at the beginning and end of the process, the flow of the consolidation procedure runs like this:

01 Locate workbooks to be processed, add them to a collection
02 For each workbook in the collection:
03 Open it
04 Read the data in the workbook into memory
05 Close the workbook
06
07 Open consolidation workbook
08 For each block of data collected:
09 write into the appropriate place in the workbook
10
11 Save and close

Now that’s all fairly straightforward. The issue I found myself faced with a couple of days ago relates to keeping the data from each of the workbooks in memory. There’s a fair variety of data in them, so I elected to use a user-defined type (UDT) to hold it:

1 Public Type uCheckSheetData
2 sLocation As String
3 dtMonth As Date
4 vErrors As Variant
5 lNumCases As Long
6 sComment As String
7 End Type

I then formed a collection which would hold the UDTs – or so I thought. For those of you who’ve tried this before, you’ve probably also seen the rather obscure error message:

Compile error:

Only user-defined types defined in public object modules can be coerced to or from a variant or passed to late-bound functions

After a fair amount of head-scratching and wtf?ing I finally decided that Google is my friend and found a solution: UDTs can’t be added to collections – use a class. Classes in VBA may not be all that they are in other languages, but they do represent a more object-oriented approach, and can accomplish all and more that a UDT can. They just represent a bit more work to code. For example, here’s how I replaced the UDT uCheckSheetData with the class CCheckSheet:

01 Option Explicit
02 ' Replaces public type as class can be added to
03 ' collections/dictionaries
04
05 Private sLocation As String
06 Private dtMonth As Date
07 Private vErrors As Variant
08 Private lNumCases As Long
09 Private sComment As String
10
11 Public Property Get Location() As String
12 Location = sLocation
13 End Property
14
15 Public Property Let Location(ByVal strIn As String)
16 sLocation = strIn
17 End Property
18
19 Public Property Get Month() As Date
20 Month = dtMonth
21 End Property
22
23 Public Property Let Month(ByVal dtIn As Date)
24 dtMonth = dtIn
25 End Property
26
27 Public Property Get Errors() As Variant
28 Errors = vErrors
29 End Property
30
31 Public Property Let Errors(ByVal vArr As Variant)
32 vErrors = vArr
33 End Property
34
35 Public Property Get NumCases() As Long
36 NumCases = lNumCases
37 End Property
38
39 Public Property Let NumCases(ByVal lIn As Long)
40 lNumCases = lIn
41 End Property
42
43 Public Property Get Comment() As String
44 Comment = sComment
45 End Property
46
47 Public Property Let Comment(ByVal strIn As String)
48 sComment = strIn
49 End Property

Now it might be argued that a lot of that code is not really necessary. I could have defined a set of public variables in the class and just exposed them that way, rather than exposing public properties with Get and Let. However, one benefit of writing these procedures is that a lot of other code can be included in them, for instance to validate the data passed in to the class members – something that has to be done outside of a UDT. There’s also the possibility to include class methods and trap events and a whole lot of other stuff, which in this case is not really required. Chip Pearson has an excellent introductory discussion of classes in VBA at Classes in VBA. Which, by the way, includes a prominent warning not to make classes auto-instancing (using Dim as New syntax when declaring a class variable, otherwise known as a really bad idea). There’s also a great chapter in the book Professional Excel Development covering classes, which also warns against auto-instancing (did I mention that was a really bad idea?).

Finally, there’s a rather interesting discussion here about why VB won’t let you add a UDT to a collection.

—————————————–

—————————————

Introduction

Classes are a powerful tool in intermediate to advanced level VBA programming. This page is an introduction to what a class and an object are and will hopefully get you started working with classes. This is by no means a comprehensive guide.

In VBA, a class is defined in class module and serves as a template for an object. The term object is deliberately vague. An object can be defined to represent whatever you want. Anything that you can describe conceptually can be represented by a class. The difference between a class and an object is that a class does nothing and consumes no memory. When you have a variable of that class type and create instance of that class with the New keyword, a process called instantiating, it becomes an object and consumes memory and can carry out actions. A class is defined by its properties, which describe attributes of the class, and its methods (sub and function procedures), which carry out actions in the object. If a class is analogous to a noun, a property is like an adjective — it describes the object. A method is like a verb — it carries out an action.

You must instantiate a class into an object in order to do anything with it. There is nothing you can do with a class module beyond creating an object from it. An example of instantiation is shown below:

Dim C As Class1
Set C = New Class1

where Class1 is the name of the class module. Unlike other languages, VB/VBA allows for only one class in a class module, and the name of the class is the name of the module.
You can now work with the properties and methods defined in Class1 in the C object variable.

NOTE: It is also possible to combine the two statements above into a single statement:
Dim C As New Class1
This is called an auto-instancing variable. When the variable C is first encountered in code, a new instance is created. In general, you should avoid auto-instancing variables for two reasons:

  • First, it adds overhead to the code because the variable must be tested for Nothing every time it is encountered in code.
  • Second, you have no way to test whether a auto-instancing variable is Nothing becaue the very act of using the variable name in an If Obj Is Nothing Then statement will automatically create an instance of the variable.

SectionBreak

Before getting in to classes and objects, it will prove useful to examine briefly a class’s logical ancestor, the Type declaration. A Type is made up of other basic variable types. You may be familiar with Types from other programming languages, in which they are called a struct, structure, or record. For example, we could declare a Type that describes an employee:

Type Employee
Name As String
Address As String
Salary As Double
End Type

This defines a single type named Employee which has three elements: Name, Address, and Salary. You can then create variables of the Employee type and give values to the elements. For example,

Dim Manager As Employee
Manager.Name = “Joe Smith”
Manager.Address = “123 Main Street”
Manager.Salary = 40000

Types are quite useful, but have three shortcomings. First, you can’t declare new instances of a Type. You must declare all the variables you’ll need at design time or you need a dynamic array that is resized with Redim Preserve, an awkward and expensive operation. The second shortcoming of a Type is that you have no control over what values are assigned to the elements of a Type. For example, there is nothing to prevent the assignment of a negative value to the Salary element. Finally, a Type can’t do anything. It cannot carry out actions; it is simply a static data structure.

While Types have their place (they are used extensively in Windows API functions), a class module is often a better solution. New instances of a class may be created with the New keyword and stored in a Collection or Dictionary object. Next, the properties of a class can be set or retrieved with Property Let and Property Get procedures, which can contain executable code. Thus, code could be written to raise an error or take other appropriate action if an invalid value is used to set a property value, such as a negative value for a Salary. Finally, classes have methods (sub and function procedures) which can carry out actions. In the example of an employee, there might be a method to print a paycheck for the employee.

SectionBreak

Class Basics

For illustration, let’s adapt the Employee Type described above into a class. First, insert a class module into your VBProject (from the Insert menu in the VBA editor). Name the class CEmployee (it is common practice to use a ‘C’ as the first letter of a class). There are three properties to create: Name, Address, and Salary. These values will be stored in private variables within the class. Since they are declared Private, they cannot be accessed outside the class module.

Private pName As String
Private pAddress As String
Private pSalary As Double

Next, we need to declare Property procedures to allow these variables to be read from and written to. This is done with Property Get and Property Let functions (or Property Set for object type variables).

”””””””””””
‘ Name property
”””””””””””

Public Property Get Name() As String
Name = pName
End Property
Public Property Let Name(Value As String)
pName = Value
End Property

”””””””””””
‘ Address property
”””””””””””

Public Property Get Address() As String
Address = pAddress
End Property
Public Property Let Address(Value As String)
pAddress = Value
End Property

”””””””””””
‘ Salary property
”””””””””””

Public Property Get Salary() As Double
Salary = pSalary
End Property
Public Property Let Salary(Value As Double)
pSalary = Value
End Property

The Get procedure is used to return a value out of the class, and the Let procedure is to put a value into the class. Note that the return data type of the Get property procedure must be the same data type as the (last) parameter to the Let property procedure. Otherwise, you’ll get a compiler error.

Because Property procedures can contain any code you like, the Let Salary procedure can be written to exclude non-positive values.

Public Property Let Salary(Value As Double)
If Value > 0 Then
pSalary = Value
Else
‘ appropriate error code here
End If
End Property

A property can be made read-only simply by omitting the Let procedure. For example, a read-only property might be withholding tax, which is calculated when it is called. E.g.,

Property Get WithholdingTax() As Double
WithholdingTax = calculated value
End Property

Finally, the class can contain methods, such as a PrintPaycheck procedure.

Public Sub PrintPaycheck()
‘ actual code to print check
End Sub

Now that we have defined the class, we can create objects based on the class. In a standard code module, declare a variable of type CEmployee.

Dim Emp As CEmployee

Then, Set that variable to a new instance of the class and assign some property values.

Set Emp = New CEmployee
Emp.Name = “Joe Smith”
Emp.Address = “123 Main Street”
Emp.Salary = 40000

SectionBreak

Storing Multiple Objects In A Collection

If you need to store multiple instances of a class, such as for a group of employees, you can create mutliple objects from the class and store them in a Collection or Dictionary object, as shown below.

Dim Employees As Collection
Dim Emp As CEmployee

Set Employees = New Collection

For Each Item In SomeList
Set Emp = New CEmployee
‘ set properties for Emp
Employees.Add Emp
Next Item

Now, you can use a simple For Each loop to loop through the collection and iterate through the collection and access each instance of CEmployee sequentailly:

Dim Emp As CEmployee
For Each Emp In Employees
Debug.Print Emp.Name
Next Emp

SectionBreak

The Instancing Property Of A Class

The Instancing property of a class controls where that class may be used. The default value is Private, which means that the class can be used only in the project in which the class is defined. You can set the instancing property to PublicNotCreatable, which allows a variable to be declared as that class type in projects that have a reference to the project containing the class. The second class may declare a variable of the class type, but cannot create an instance of the class with the New keyword. See the next section for more details.

SectionBreak

Self-Referencing An Instance Of A Class

Code within a Property or method of a class can refer to its own instance by using the Me reference. For example,

    Private pName As String
Property Let Name(S As String)
pName = S
End Property

Public Sub SomeMethod()
''''''''''''''
' some code
''''''''''''''

Me.Name = "ABCD"
End Sub

This refers to the Name property of the instance of the class from which it is executed.

SectionBreak

Using Classes In Multiple Projects

If the Instancing property of the class is PublicNotCreatable a variable of that class type may be declared in other projects, but cannot be created in that project. You can use a function in the project containing the class to return a new instance to the caller. First, change the name of the project containing the class from the default value of VBProject to something meaningful like projSourceProject. Then, in the class that will use the class, set a reference to projSourceProject. Back in the project containing the class, create a procedure that will create and return a new instance of the class:

Public Function GetClass() As CEmployee
Set GetClass = New CEmployee
End Function

Then call this function in the project that will use the class:

Dim NewEmp As projSourceProject.CEmployee
Set NewEmp = projSourceProject.GetClass()

SectionBreak

Setting The Default Value Of A Class

You can specify a property to be the default property of a class. When you do this, you can omit that property name and the compiler will use the default property. For example if you made Name the default property, the following lines of code are functionally equivalent:

Emp.Name = “Joe Smith”
Emp = “Joe Smith”

See Default Property Of A Class for information and examples of creating a default property.

This page just scatches the surface of what you can do with classes. Consult a good book on VBA or VB6 programming for a more in depth treatment of classes.

This page last updated: 20-July-2007