A 6-Pack of Good Programming Style Hints  | Expert | | Join Date: Apr 2006 Location: Philadelphia
Posts: 5,218
# 1
May 6 '07
| | - Indent - A procedure normally has several sections. There may be a section for error-handling code, groups of code lines for repetitive operations, alternative groups of statements to be executed under some conditions but not under others, etc. Indenting is a useful way to identify code sections. Although it makes absolutely no difference to the compiler, it does make your code easier to read and understand.
- Do
-
movespot = movespot / 2
-
MyRS.Move (movespot)
-
If StrComp(MyRS![LastName], searchadv) < 1 Then
-
ElseIf StrComp(MyRS![LastName], searchadv) = 0 Then
-
MsgBox "Exact Match"
-
Else
-
MyRS.Move (0 - movespot)
-
If Not MyRS.EOF Or MyRS.BOF Then
-
MyRS.MoveFirst
-
End If
-
End If
-
Loop Until movespot < 2
- Use Comments - As you are creating code, the purpose and logic of a procedure's statements may seem obvious. Days or weeks later, the logic may be elusive to you and downright confusing to someone else. Save yourself and others time and effort by commenting your code. Comments should be included at the beginning of a procedure to describe the procedure's purpose, the arguments, and the value returned if a function procedure. It is not necessary to comment every line of code, in fact it is down right excessive, but you should at least include a comment to explain the logic of each group of statements. To designate a comment line, procede it with an apostrophe. By default, the VB Editor will change comment lines to green.
- 'Make sure to 1st set a Reference to the Microsoft Excel XX.X Object Library
-
Dim objExcel As Excel.Application
-
Set objExcel = CreateObject("Excel.Application")
- Use Naming Conventions - It is very important to establish a consistent pattern for naming objects you create in your applications. With a properly chosen, consistently applied naming convention for procedures, objects, constants, and variables, your VBA code becomes more self-documenting and easier to understand.
- Dim strLastName As String
-
Dim lngZipCode As Long
-
Dim blnFoundFile As Boolean
-
Dim dteBirthDate As Date
-
Dim rstNew As Recordset
-
Dim dbNorthwind As Database
-
Dim dblPie As Double
-
Dim astrEmployees(100) 'an Array of Strings
-
fExtractMiddleInitial(strFullName As String) As String 'Function
- Use Separate Lines For Each Statement - Although you can string together several statements separated by colons on a single line, avoid the urge to do so. The advantage of condensing your code is more than offset by the increased difficulty in reading it.
- Do While Not MyRS.EOF
-
'Avoid 2 statements on a single line
-
Debug.Print MyRS![LastName]: MyRS.MoveNext
-
Loop
- Use the Line-Continuation Character - As you have probably noticed, the Module Window does not have a word-wrapping feature. If you enter a very long statement, you can wrap the statement yourself by use of the line-continuation character wich consists of a space followed by an underscore ( _). If you don't break a long line with this character, you will need to use the horizontal scrollbars to view parts of the statement. You can't use the line-continuation character to wrap a string expression to another line; instead, you can divide the string into smaller pieces and concatenate the pieces.
- Dim strMsg As String
-
'Instead of this
-
'strMsg = "The rules of Referential Integrity have been violated. You have made an attempt to enter a Training Record for an Employee in the Training Table when this individual doesn't exist in the Parent (Employees) Table. Enter a valid Employee Record first, then proceed"
-
-
'Use this syntax
-
strMsg = "The rules of Referential Integrity have been violated. You have made an " & _
-
"attempt to enter a Training Record for an Employee in the Training Table " & _
-
"when this individual doesn't exist in the Parent (Employees) Table. Enter " & _
-
"a valid Employee Record first, then proceed"
-
-
MsgBox strMsg, vbExclamation, "Referential Integrity Violation"
- Declare Variables and Constants at the Beginning of a Procedure - By grouping all declaration statements at the beginning of a procedure, you can see the constants and variables at a glance and avoid needing to hunt through procedure code to find them.
- Private Sub_SomeButton_Click()
-
Dim dbMyDB As Database, rstMyRS As Recordset, intNoOfRecords As Long
-
Dim intCounter As Integer, tdfNew As DAO.TableDef, fldOld As DAO.Field
-
End Sub
| | Newbie | | Join Date: Jan 2008
Posts: 1
# 2
Jan 9 '08
| | | re: A 6-Pack of Good Programming Style Hints
I generally use Javascript as my scripting language along with ASP.
I have noticed that VBscript developers tend to initialize a group of constant global variables a the beginning of a script even though the script may only use that variable once. Since each variable takes up precious memory resources and the constant variable is already a literal string anyway; wouldn't it be better to use the literal strings hard coded into the script or application if only being used once or not at all in some cases, to free up memory resouces in an application.
|  | Expert | | Join Date: Apr 2006 Location: Philadelphia
Posts: 5,218
# 3
Jan 9 '08
| | | re: A 6-Pack of Good Programming Style Hints Quote:
Originally Posted by ASPDeveloper I generally use Javascript as my scripting language along with ASP.
I have noticed that VBscript developers tend to initialize a group of constant global variables a the beginning of a script even though the script may only use that variable once. Since each variable takes up precious memory resources and the constant variable is already a literal string anyway; wouldn't it be better to use the literal strings hard coded into the script or application if only being used once or not at all in some cases, to free up memory resouces in an application. I agree with you wholeheartedly, ASPDeveloper. To Declare a series of Constant Variables Globally, when used in the context of single usage, is a waste of System Resources. In these cases, it is my opinion that the Variables should be hard coded into the Script/Application.
|  | Administrator | | Join Date: Oct 2006 Location: London - UK
Posts: 15,730
# 4
Aug 30 '09
| | | re: A 6-Pack of Good Programming Style Hints
Just for reference, I'd like to state that I disagree fundamentally with the ideas posted by ASPDeveloper.
Not that I'm saying efficiency is unimportant. Far from it. Simply that code organisation and consistency plays a very important role in code maintenance, and code maintenance is such a supremely important (and criminally undervalued so often) aspect, that this level of code inefficiency is entirely negligible when compared with the relative ease of maintenance that comes with tidy and consistent coding.
I would say pay close attention to ADezii's six tips. These are all worthwhile concepts to take onboard. If you're not doing them already, then start ASAP.
|  | Expert | | Join Date: Apr 2006 Location: Philadelphia
Posts: 5,218
# 5
Aug 30 '09
| | | re: A 6-Pack of Good Programming Style Hints Quote:
Originally Posted by NeoPa Just for reference, I'd like to state that I disagree fundamentally with the ideas posted by ASPDeveloper.
Not that I'm saying efficiency is unimportant. Far from it. Simply that code organisation and consistency plays a very important role in code maintenance, and code maintenance is such a supremely important (and criminally undervalued so often) aspect, that this level of code inefficiency is entirely negligible when compared with the relative ease of maintenance that comes with tidy and consistent coding.
I would say pay close attention to ADezii's six tips. These are all worthwhile concepts to take onboard. If you're not doing them already, then start ASAP. Are we digging up the past, NeoPa? (LOL)
|  | Administrator | | Join Date: Oct 2006 Location: London - UK
Posts: 15,730
# 6
Aug 31 '09
| | | re: A 6-Pack of Good Programming Style Hints Quote:
Originally Posted by ADezii Are we digging up the past, NeoPa? (LOL) I'm planning to refer to this and a bunch of other good articles ADezii. This invariably means that I visit them (and maybe even add some comments).
I certainly don't see popular articles as dead threads. If any good ones appear dead or old, then possibly it's time to change that ;-)
|  | Expert | | Join Date: Apr 2006 Location: Philadelphia
Posts: 5,218
# 7
Aug 31 '09
| | | re: A 6-Pack of Good Programming Style Hints Quote:
Originally Posted by NeoPa I'm planning to refer to this and a bunch of other good articles ADezii. This invariably means that I visit them (and maybe even add some comments).
I certainly don't see popular articles as dead threads. If any good ones appear dead or old, then possibly it's time to change that ;-) Just thought that you liked my Articles! (LOL)
| | Expert | | Join Date: Jul 2008 Location: Maryland
Posts: 1,176
# 8
Aug 31 '09
| | | re: A 6-Pack of Good Programming Style Hints
I have to agree with NeoPa. ASPDeveloper seems to have missed one of the main points of using constants, even with the (negligible) cost to "precious memory resources".
|  | Expert | | Join Date: Sep 2007
Posts: 273
# 9
Sep 17 '09
| | | re: A 6-Pack of Good Programming Style Hints
Excellent tips here, but what about the tools out there that allow one to do these things quicker? Here is a listing of the FREEWARE VB Editor tools I use to streamline my code. These tools help with almost all of the tips ADezii posted, by automating processes or allowing one to make lightning-fast corrections.
I've been using these for a few years now, and I'd be absolutely lost without them now. I've posted the homepages, names, and the description from each tool as they are on their homepages.. but these are very general descriptions. Detailing what these can all do would take quite a while.. its' best to just pick them up, install them onto your system, and make sure the toolbars in your VB Editor are visible. These all have Right-Click menu options, as well as detailed setup screens accessible from the toolbars to allow you to further customize the procedures, set defaults, etc. Office Automation Ltd - Stephen Bullen http://www.oaltd.co.uk/ Smart Indenter (IndenterVBA.exe v3.5) http://www.oaltd.co.uk/Indenter
"These COM Addins for the Office 2000-2003, Excel 97 and Visual Basic 6 IDEs are the latest updates for the popular Smart Indenter utility. It adds the ability to rebuild all the indenting for a VBA procedure, module or project (i.e. indenting after each If, For etc and outdenting before each End If, Next etc.). The routine handles all valid VBA constructs, including line continuations, multi-statement lines and conditional compilation items and works within all of the Office products and any other VBA6 host." VBETools.exe v2.0 http://www.oaltd.co.uk/VBETools
"This COM Add-in adds a number of features to the Office VBE, including: - Close all open windows in one click
- Display the size of the active module on the toolbar
- Rename controls and update the code that uses them
- Modify the Tools > References dialog to display the full path of any references
- Accurately Move and size userform controls pixel-by-pixel
More information and screen shots can be found on the VBE Tools page." MZ-Tools http://www.mztools.com MZ-Tools 3.0 for Visual Basic 6.0, 5.0 and VBA (40+ Features)
"MZ-Tools 3.0 is a freeware add-in for Visual Basic 6.0, Visual Basic 5.0 and the Visual Basic For Applications editor (provided by a VBA-enabled application such as those in Office 2000-2007) which adds several productivity features to the IDE.
MZ-Tools is very easy to use. It provides a main menu, a toolbar, handy context menus and customizable shortcuts to access its features, which are detailed in the Features section.
You can customize several features of MZ-Tools to meet your development standards (data type prefixes, template for procedure headers, template for error handler, etc.) or your personal preferences (user name, shortcuts, etc.)
For your convenience, MZ-Tools has been localized in the following languages: English, Spanish, French, Italian, German and Portuguese (Portugal).
MZ-Tools will allow you to enjoy the following benefits during the development of your applications: - To write code faster: There are features that will allow you to insert exception handlers, snippets of code, etc. with a single mouse click, keyboard shortcut or expansion keyword, and to use assistants to create new procedures, message boxes, connection strings, etc.
- To find code faster: With the enhanced Find feature of MZ-Tools, all the results are shown in a hierarchical tree inside a dockable window that allows you to remove occurrences that are not of interest. Other features allow you to find all code locations that call a given procedure, to keep a list of favorite procedures, etc.
- To design forms faster: There are features that will allow you to apply default properties to a control when it is added to a form, to set the TabIndex property of all the controls of a form with one click, etc.
- To document your code faster: There are features that will allow you to insert headers (to a procedure, class or file) with a single mouse click or keyboard shortcut. These headers are customizable and allow the use of predefined variables (such as the procedure name) or user-defined variables. Furthermore, other features will generate documentation about your source code in XML and HTML formats.
- To ensure the quality of your code and applications: There are features that can sort code, add line numbers for error handlers, code reviews that can detect dead code, review the TabIndex or access keys of your controls, review forbidden or mandatory text, etc. Even better, from version 4.0 for Visual Studio .NET onwards you can use the MZ-Tools SDK to write your own review operations with very little effort.
- And many more features (40+ in each toolset) to make coding more enjoyable by eliminating the tedious tasks!"
If anyone else has any good freeware tools they've found they simply cant live without, I'd like to hear about them.
Also, I've been using these extensively in Office 2007, and have verified they work fine in Office 2010. So even though most of these utilities havent been updated since 2003, dont worry about compatability.
|  | Expert | | Join Date: Apr 2006 Location: Philadelphia
Posts: 5,218
# 10
Sep 18 '09
| | | re: A 6-Pack of Good Programming Style Hints
Great job Megalog, looks like some very useful, practical, and interesting Resources that you have listed here. Thanks for the effort.
|  | Similar Microsoft Access / VBA bytes | | | /bytes/about
We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights.
Get the best answers to your questions from over 226,471 network members.
|