I stand by my recommendation.
Using "For i = j to k" is ok for homework, but is a bad habit to get into for production work.
ALWAYS assume your little bit of code will be built upon, expanded, or become part of a larger project. A few seconds spent up front could save hours later.
I've had to clean up too many instances of other people's code that was like this:
50 lines into the code, my head is spinning when I run into a line like:For i = j to k Step p For x = y to z If a > b Then '....many lines of code Else '....many lines of code End If Next Next
"If i < z Then"
I see. You still have a global variable but it's more obvious and with centralised control over possible bad states.
For scoping I keep it as local as possible with prefixes to identify the scope as well as variable type.
strA ' local to routine m_strA ' local to module g_strA ' local to project
I agree with you that using some sort of notation like the hungarian notation would help maintain (and understand) the code.
... and do we now ALL promise to use this in our Forum answers ? or do we consider that as homework?
Looking for great solutions but hate waiting?
Seach this Forum through Google
www.Google.com (e.g. +multiple +IF site:excelforum.com/excel-general/ )
www.Google.com (e.g. +fill +combobox site:excelforum.com/excel-programming/ )
Ave,
Ricardo
It's homework until I get my honorary doctorate from the University of Excel!!!
Dom
"May the fleas of a thousand camels infest the crotch of the person who screws up your day and may their arms be too short to scratch..."
Use code tags when posting your VBA code: [code] Your code here [/code]
Remember, saying thanks only takes a second or two. Click the little star to give some Rep if you think an answer deserves it.
I agree to continue using descriptive variables in posts.
In our responses, we are teaching proper methods for solving Excel issues.
While inefficiencies in formatting, functions, and sheet structure are usuallly easy to correct,
poor programming habits in small projects turn into poor programming in large projects
that can be a nightmare to fix. Best to prevent them at the beginning.
Hmmm
But you see it is only useful very locally (in this case for one line). Sometimes it takes several lines to compile the select statement.str = str & " where c2.IsReal=""Y"" and [c2].[Include] = true " 'don't include non partners Set rstAllPartners = db.OpenRecordset(str) IsFirstPass = True
![]()
Hope this was useful or entertaining.
I think Richard was referring to the fact that str is a native VBA function...![]()
Originally Posted by David
The error occurs when you do a Replace across the workbook (from the UI, per force), then a range.Replace from VBA. The range is ignored and replacement is performed throughout the workbook. Specifying all the parameters of the Replace won't help; you have to do a dummy Find to reset the behavior:Originally Posted by Dom
The word Texas is key here ...Set r = Worksheets(1).Range("A1").Find(What:="Texas", LookIn:=xlFormulas)
Don't know if this has been corrected.
Here's my list:
1) Variables a) Pick a variable naming convention and follow it. b) Declare all variables appropriate to usage. c) Use Variants only when necessary, to wit: i) To receive an argument that may be of varying type (string, Boolean, number, or arrays of same) ii) To receive a value from a cell than may be of varying type iii) To receive the value of a multi-cell range from a worksheet iv) To receive an indefinite number of arguments (ParamArray is a variant) v) To receive the results from many worksheet functions, like MMult (I'd have thought that a dynamic array of Doubles would work, but I couldn't get it to) and Array vi) To receive the value of a property that may return Null (e.g., Selection.Interior.ColorIndex for a non-homogeneous selection) vii) To receive the keys of a dictionary viii) To be the control variable of a For Each loop when not a more closely-aligned data type is available (e.g., a Range) ix) To be the return type of a function that returns data of varying type, or (on Mac, I’m told) an array of variable size 2) Don’t select cells, sheets, workbooks, or other objects except as necessary 3) Code structures: a) Generally, use built-in (worksheet) functions when possible (there are some exceptions). b) Don’t use loops if there’s a way around it; if there isn’t, prefer iterating elements from a collection (For Each/Next), followed by For/Next and Do/Loop. c) Select Case statements are prettier, If/ElseIf/Else/EndIf statements are faster (curious; you'd think the compiled code would be the same). Either should be arranged to test cases from most likely to least. d) Use collections and dictionaries in preference to other data structures when possible. e) Don't use Option Compare Text; there are better options. f) Use the Like operator sparingly. Ditto for Regular Expressions. Avoid text comparison entirely when there are other options (e.g., TypeOf versus TypeName) g) The Len function is among Excel's fastest; all it has to do is grab the first word of a string, where the length is stored. So rather than If s <> "", use If Len(s) (and there’s no need to coerce a number to a Boolean so it can be converted back to a number) h) Use early binding for objects unless you have specific reason not to. i) Write logical, clear code first, and then optimize for speed. Don’t obscure the structure and intent of code for speed unless you don’t mind having the person that has to maintain it later casting aspersions on your lineage. j) Comment your code minimally beyond the procedure level; it’s impossible to keep code and comments in sync. Instead, make code shine in clarity and simplicity. 4) Speed a) Set Calculation to manual during execution. If worksheet calculation is necessary in the course of macro execution, calculate only the minimum range necessary. b) Turn off ScreenUpdating during execution c) Turn off events if necessary to avoid triggering change event macros and getting other listeners excited
Microsoft MVP - Excel
Entia non sunt multiplicanda sine necessitate
This thread has started humming since I last saw it!
Shg, I can't remember having ever seen a code snippet on the Forum that uses TypeName or VarType etc & I'm going to have go investigating now!
I may have missed this in amongst the posts, but what is the general consensus on explicitly naming arguments vs using commas as placeholders in argument listings?
For example:
I try for the latter, but I know I'm guilty of the former, & it's usually when I can see the OP is likely to have some understanding of the code already. In other words, I'm probably reinforcing existing bad habits & showing the new folk to "do as I say rather than do as I really do"...MsgBox "done", , "FINISHED" MsgBox prompt:="done", Title:="FINISHED"
Rob
Rob Brockett
Kiwi in the UK
Always learning & the best way to learn is to experience...
shg: as articulate as ever. It's always a pleasure to read your posts. I wonder if you might expand on your reasoning behind
andprefer iterating elements from a collection (For Each/Next), followed by For/Next and Do/Loop.
broro183: fwiw, I'm inconsistent. With Find I explicitly name the arguments I specify (not necessarily all of them), but for Copy/Paste I never specify Destination. I suppose good practice would be to name them all, but I think given most of us have limited time on the forum we tend to cut corners. I have to confess that I am probably more thorough when writing code for my own use.Use the Like operator sparingly. Ditto for Regular Expressions.
Just be aware that TypeOf and TypeName don't do the same thing and TypeName is better in certain situations.
Indeed, and I believe you gave me an good example with controls some weeks ago.Just be aware that TypeOf and TypeName don't do the same thing and TypeName is better in certain situations.
Maybe this is a better example of avoiding a text comparison:
Set wks = Worksheets("Sheet1") If wks Is Sheet1 Then MsgBox "True" ' is better IMO than If wks.CodeName = "Sheet1" Then MsgBox "True"
Last edited by shg; 02-18-2010 at 05:30 PM.
Microsoft MVP - Excel
Entia non sunt multiplicanda sine necessitate
Thanks Shg & RS,
"TypeOf" is my little learning for today - it seems to be hidden away in the 2007 Help files under "If...Then...Else Statement".
My investigations/Google shows an incy squincy total of about 100 results in the Forum for the below three data information functions: http://www.google.co.uk/search?hl=en...meta=&aq=f&oq=
Could/should we be more defensive when offering solutions?
StephenR, I'm pleased I'm not the only inconsistent one - your logic is sound too.
Rob Brockett
Kiwi in the UK
Always learning & the best way to learn is to experience...
My understanding is that iteration and search of collections and dictionaries are very fast and highly optimized. They are also very intuitive stuctures, IMO. Beats the heck out of redimensioning dynamic arrays in a loop.expand on your reasoning behind
andprefer iterating elements from a collection (For Each/Next), followed by For/Next and Do/Loop.
Use the Like operator sparingly. Ditto for Regular Expressions.
RegEx and it's little brother, the Like operator, entail complex comparisons; think about the difficulty of writing one, and then stop when you feel a blood vessel approaching the bursting point in your brain. They're great tools, just limit their use to when they are justified.
Like is so easy to use that I abuse it, I confess.
Last edited by shg; 02-18-2010 at 05:31 PM.
Microsoft MVP - Excel
Entia non sunt multiplicanda sine necessitate
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks