How to change a global variable name in an Excel VBA project? - vba

If someone have to carry on working on an Excel VBA project/module after the previous developer left the company, how do they safely change a global variable name?
These global variable names can be problematic if they are misleading, misspelled, look like another variable, don't follow the chosen convention, etc.
Changing them with a Search/Replace is a problem because sometimes it's a word that appears in comments.
Changing them by Copy/Pasting is a problem because it's long and you can miss some, especially if there are a lot of occurrences or if you change it to something similar.
Is there a way to do this safely via the Excel "IDE", or via another tool?

What you need to do here is called a refactoring - you need to make a possibly dangerous change to the code, without affecting its behavior. Do it wrong and the code breaks!
Renaming an identifier that's used in one or more places, is a rename refactoring.
Most modern IDE's have such a feature (and several other refactorings). However the VBE was at the height of its glory well before Visual Studio was the full-featured tool it has become since then - heck, the VBE was Visual Studio (6.0) in 1998!
So you really have two options:
Do the refactoring manually - the IDE's search & replace functionality (Ctrl+H) can be dangerous here, because it treats code as simple text, without semantic understanding: you need to review every single occurrence individually, or risk renaming an identifier that was not referring to the variable you're trying to rename.
Use a 3rd-party tool - I don't know any VBIDE add-ins that understand the code deeply enough to allow safely refactoring VBA code, other than the open-source Rubberduck project, which I've managed since October 2014). This add-in parses your entire project, builds a symbol table, and lets you navigate and, yes, refactor/rename any identifier, automatically updating all call sites.
Note that Rubberduck is a very active open-source project, constantly improving. Parsing VBA is hard, and getting the VBE functionally on par with modern-day IDEs isn't a small undertaking, nor is it easy... but it's fun, and yep, it works.

Related

VBA external modules

Is it possible to have modules be external to the actual Excel file and call the functions/subs within them externally?
My thinking is if there are multiple Excel files that use the same module, instead of updating each one of those files separately when I make a change, can I just update the one module stored on a server or something?
I have doing something like you describe for years. You can move your VBA code to a VB6 ActiveX dll, organize it into classes, and load that dll as a reference from Excel VBA.
This is a good way to reuse non-workbook specific code. For instance, I have code that queries a mainframe. I like to call it from Excel, but the details of the connection and how data is passed are contained in a dll that I can load from Excel, VB6, Word, .NET, wherever. I have a similar dll for reading data from AutoCAD drawings, one for interfacing with a product DB on a MySQL server, etc.
The code that remains in Excel tends to be simple formatting stuff. Say I return a variant array of strings (technically a COM SAFEARRAY) from some library that I wrote. I would then output it into Excel, maybe do a text-to-columns, and have a list of results returned to the user.
You can also pass and return more complex data structures. The beauty of VB6/COM Automation (and I didn't appreciate this until I learned to do it the harder way in VB.NET or C#) is that the data will flow in and out of your components seamlessly and all the necessary interfaces will be created for you.
The main change to your code will be replacing things like ThisWorkbook or ActiveSheet with explicit parameters like (Byval sht as Excel.Worksheet). These will be caught at compile time in VB6 (since it doesn't know what ThisWorkbook is), so you cannot overlook them; you are forced to pass an explicit reference.
I also notice that my code inside the dll becomes more paranoid if it receives a Worksheet or other Excel object as a parameter. In VBA you might have had more assurance that you were passing a good object since it was private to a given workbook. The dll does not know who is calling it, so I view the passed-in object with more suspicion (check if Nothing, sheet name, formatting clues to ensure I am using what I think I am using).
The only downside I see is that you will have to get a copy of Visual Basic 6.0. I bought mine in 1998. It is no longer available from Microsoft, but surely there is someone out there who will sell it to you. The latest service pack is SP6.
You will also have to become familiar with "regsvr32" and "regsvr32 /u" to deal with the "ActiveX can't create component" errors as you open your workbooks on various computers. I just publish my dlls to a mapped network drive and re-register them on the user's computers whenever there is a significant change. Obviously this is a intranet/single company solution. Publishing the updated versions is much more of a pain the farther you are distributed.
Not sure if this would satisfy your needs, but you could create your common module as an "add-in" and so install it so that all files that you open in the same instance of excel would have access to the add-in code.
It would not be my recommended way of doing it because I would be worried about suitable testing of all the excel files that use it, when you make a change, plus the added complexity of getting users to install your add-in (this may not be an issue for you). I have a "developersToolkit" module I use across 8 different Workbooks, but I import the module into each workbook so its stand alone and I can also test changes for compatibility with each of the 8 workbooks.

Missing referencies in VBA: how to "include" modules?

I have a legacy code - some macro for Autocad - and I got it running on Autocad 2015 with enabled VBA. There are some string-related function as Trim, Mid, etc.
And these functions are missing references, VBA can't find their definitions. I can find them manually in object browser, so I use Strings.Trim and it works. How can I avoide adding module name to every call of the function in VBA? Is there something like include String'?
Edited: I got a compile error "Can't find project or library" and here is a screen shot of References window just after this message:
And Microsoft Word Library is selected be default. I double-checked, the path to it is correct.
There is no libraries with MISSING prefix (or just can't see it). Maybe, some of them must be excluded since it is a legacy code, but I am not sure wild guessing will be fine in this case, maybe there is a way to get problem libraries marked?
It is possible one of your references (newer versions of AutoCAD, or more likely Microsoft Word) now has function or method names matching Left, Mid, Trim and so on, that didn't exist before. This will make those function names Ambiguous.
Try selectively removing references to see the effect on those functions, or observe the intelliSense when typing Mid to see if it has a different meaning.
Consider writing wrappers for those string functions. For example, write a Left function that internally calls strings.Left in a module visible to where those functions are used.
While this doesn't solve your problem immediately, it will allow you to minimise changes to the legacy code.

VBA and late binding: Where do I find the numeric equivalents to constants?

I'm a complete VBA newbie, having decided to teach myself over a weekend, so forgive the stupid question(s). I'm trying to automate some routine tasks involving generating Word documents or emails from an Excel Spreadsheet. Because there will be multiple software versions involved, I am using late binding to open Word and Outlook. My question is: Where can I find a simple reference telling me what the index numbers are that correspond to the application constants? I have killed a lot of time googling to learn that, for example, the Outlook foldertype for "Contacts" is "10". Maybe someone knows of a web link that could save me countless hours of searching?
Update: http://msdn.microsoft.com/en-us/library/office/gg278936%28v=office.14%29.aspx seems to have some of the information I need, although it's not always intuitive where the information is. For example, if it contains the outlook folder type constants, I haven't found them yet.
See here
Enumeration http://msdn.microsoft.com/en-us/library/office/ff860961(v=office.15).aspx
OlDefaultFolders Enumeration http://msdn.microsoft.com/en-us/library/office/ff861868(v=office.15).aspx
I would recommend to add the relevant object libraries to your project as References during development time. You do this by using the Tools - References Menu in the VBA Editor. This makes developing a lot easier as you can use intellisense while writing the code.
If you need only a few Enums or single Constants in your code the easiest way to get their values is to hit [F2] in in VBA Editor while the object libraries are still referenced. Then search for the constants name and copy its value to your code.
Just using the numeric values of the constants in your code makes the code pretty hard to read. So I would recommend to re-declare all the Enums/Constants you actually use in a module in your own project. That massively improves the readability of your code.
So, instead of just copying the value from the VBA Object Browser, I suggest you copy the name and the value and put it your own code as a constant declaration. For your example of the Outlook contacts folder this will look like this:
Public Const olFolderContacts = 10
You can then use the constant in your procedures as you would do with Early Binding.
Should you work on a larger automation project using many of the constants from any one of the Office Object Libraries, you can download ready-made VBA modules containing all the Office constants from my website. You can then just import the relevant modules into your project and are ready to go.
After you finished the main development work, you remove the linked libraries from your project and declare the relevant object variables As Object instead of the actual type.
Always remember to compile your project not to miss any declaration that does not work late binding.

Can I do VBA programming with Vim?

Part of my job right now is to build some dynamic functionalities into Microsoft Office documents. The only means I've found to do this is through VBA - and thus, the VBA editor which comes built in to Office docs.
The VBA editor is awful. It's missing a million different functionalities that modern development environments need to support. But the worst part is that I'm a hard-core Vim lover, and the VBA editor is barely any better than notepad.
So: Is there any way I can effectively use Vim to do VBA programming? Short of copy-pasting my code into the VBA editor from a different window when I want to try it?
I've never used the VBA editor, but here's something I've done with MS Visual Studio. (MSVS's editor does have some nice features, but I still prefer vim for most editing.)
I open or create the source file in MSVS. I then get the full path to the file (by right-clicking on the tab and selecting "Copy Full Path"), and open the same file in vim in a different window.
I use alt-tab to bounce back and forth between vim and MSVS. When I make a change in vim, I use :w to write the change, then alt-tab back to MSVS. The MSVS editor notices that the file has changed on disk and offers to read the updated version.
Alternatively, if I change the file in MSVS, I write the file (File > Save ...), then alt-tab to vim and use :e! to read the updated file into the vim buffer.
There's no need to copy-paste the code, since both editors are operating on the same disk file. I just have to be very careful not to make changes in both vim and MSVS without writing the file to disk.
It's ugly, and it's not for everyone, but it works for me. Maybe it will work for you.
I use Cygwin, so it's actually a little more complicated; Cygwin programs, including vim, don't recognize Windows-style paths. I can do this:
vi $(cygpath 'WINDOWS_PATH')
where WINDOWS_PATH is pasted from the full path I get from MSVS. The single quotes are necessary to keep the shell from interpreting the \ characters. If you're using a Windows native vim, this step isn't necessary.
That's an interesting opinion. I used VI briefly about fifteen years ago and based on that I contend that the VBA editor is far more suited to its purpose than VI (or VIM?) would be. Is there one particular piece of functionality that it is missing from the VBA editor that precludes you effectively using it for its purpose (editing VBA)? VBA has not been enhanced for many many years, but the fact is it can't be killed off because everyone finds it so easy to use.
If you wish you can write some piece of code in your preferred language that manipulates your word document via COM objects (if it supports that). Then you can call your external piece of code from a simple stub within your Word document. You need to get around some security constraints though in your Word document.
For example I could write some code in VBScript or VBA or Powershell or .Net that manipulates a word doc. I can call that from a small piece of VBA (that might be attached to a button or something in the standard word toolbar)

Batch source-code aware spell check

What is a tool or technique that can be used to perform spell checks upon a whole source code base and its associated resource files?
The spell check should be source code aware meaning that it would stick to checking string literals in the code and not the code itself. Bonus points if the spell checker understands common resource file formats, for example text files containing name-value pairs (only check the values). Super-bonus points if you can tell it which parts of an XML DTD or Schema should be checked and which should be ignored.
Many IDEs can do this for the file you are currently working with. The difference in what I am looking for is something that can operate upon a whole source code base at once.
Something like a Findbugs or PMD type tool for mis-spellings would be ideal.
As you mentioned, many IDEs have this functionality already, and one such IDE is Eclipse. However, unlike many other IDEs Eclipse is:
A) open source
B) designed to be programmable
For instance, here's an article on using Eclipse's code formatting functionality from the command line:
http://www.peterfriese.de/formatting-your-code-using-the-eclipse-code-formatter/
In theory, you should be able to do something similar with it's spell-checking mechanism. I know this isn't exactly what you're looking for, and if there is a program for doing spell-checking in code then obviously that'd be better, but if not then Eclipse may be the next best thing.
This seems little old but seems to do a good job
Source Code Spell Checker