How to Reuse Code with VBA - vba

What is the best way to avoid duplicating code when working in VBA?
I'm used to languages where I can just add an import statement and get access to all a class's public properties and functions, so I can just create a utility class with some common functions and have access to that in any project I choose to import it to. Any time I want to update one of those functions, one edit is all it takes to get it working across all projects.
Is there any good way to replicate this functionality in VBA?

What follows focuses on Excel but I am pretty sure the same would apply to any Office products.
The easy way is to save your reusable code as an addin (*.xla for Excel 2003, *.xlam for Excel 2007+). You then add the addin to Excel and all the spreadsheets you open will have access to the custom functions you have in your addin. If you add specific VBA code to a spreadsheet, you can add a reference to your addin and your VBA code will have access to all the public sub, function and classes of your addin.
In my organisation, we use 3 home made addins - they are stored in C:\Program Files\OrganisationName. And everybody has access to them. When an update is made, we only need to copy the new version to everybody's hard drive and restart Excel and they have the new version.
The addins contain utilities functions such as functions to:
read data from / write data to spreadsheets / files / databases.
usual data manipulation such as removing duplicates from a list
advanced statistical functions
etc.
A few drawbacks:
If you have several instances of Excel open, only one can update the addin, the other instances are in read-only mode
If Excel crashes, the auto recovery mode generally does not save the changes you made on your addin (TBC on newer versions) - there are a few tools to auto save regularly
An alternative is to develop xlls or COM libraries in VB or C# for example, but this is something I have not tried.
There are plenty of tutorials online if you need a more detailed procedure.

Related

Is it possible to create Excel VBA Code Library that several workbooks share?

I have several workbooks that have similar and reused VBA code sometimes I need to update the code and I would like to do this in one place instead of in 20 different workbooks is this possible?
If not is there a way to copy all the macros from one workbook to all the others after a change has been made?
Yes, you can reference other workbooks from VBA. Might be easiest to put it in an addin though.
If you are using class modules, then you can only set them as either private or public not createable (something like that). Obviously they'll need to be public, but you can get around the inability to create them by building simple helper functions in a normal module that do nothing other than create a new instance of the class and return it.
It is possible, yes.
This answer on SU mentions one possibility that is explored more in-depth in this support article.
If you find yourself recreating the same macros, you can copy those
macros to a special workbook called Personal.xlsb that is saved on
your computer.
By default, when you create a macro in Excel, the macro works only in
the workbook that contains it. This behavior is okay as long as you
don’t need to use that macro in other workbooks. Any macros that you
store in your personal workbook on a computer become available to you
in any workbook whenever you start Excel on that same computer.
In short: record a macro and choose to save it in Personal Macro Workbook. Save and exit, then re-open Excel. Go to the View-tab and click unhide.
The support article gives a more detailed step-by-step.
Sure is possible,
the two ways that I know are:
copy your macros on Personal.xlsb (like Vegard wrote) or (it's my usually case because I've also my custom Ribbon to play all my custom cmd) you can open a new excel file, write in this file all your macro/function/class.... and then save it as xlam file.
After you need to go on excel option, add components and choice the xlam file before created.
Tips, in the xlam file use a specific macro names and not macro1, macro2,.... because into your next files will be easy to create more macro and use the same name is usually..
I'll add my answer based on experience as it seems the ones given are all (unspoken) focused on being "free".
I started out using a workbook as my code library (as suggested above), but every time I made an adjustement or improvement to those code snippets, I had to go back to the other workbook and update it etc. This got old fast.
Once I started developing a bit more professionally, it made sense to invest in a tool to manage my code.
I use MZTools which also comes highly recommended by various Excel MVPs such as Ken Puls, Ro Bovey, etc. but there are other ones out there. Usually these tools also provide addtional functionalities that are useful to a developer. Invest a few bucks if you want to save your self from a headache.

In Word 2010, export multiple VBA modules and user forms at once

As I have to give up my old laptop and migrate with all my important stuff to a newer and more powerful machine, I now want to transfer all my MS Word (MS Word 2010) macros and user forms to the new machine (also MS Word 2010).
In the VBA editor, there is an option to export individual (!) modules and user forms (--> File --> Export file). But this seems to work only for one item a time. I have dozens of items and want to export all of them at once. Is there a way to do this?
(I have read How To Deploy Word 2010 Macros To Others?, but this does not help here.)
Update: My question was based on the assumption that transferring normal.dotm to the new system would not transfer the macros and user forms too. I now see that this assumption was wrong: indeed, transferring normal.dotm to the new system (in Windows 7, this would usually be in c:\users[user name]\AppData\Roaming\Microsoft\Templates), seems to include VBA modules and user forms. However, there might be situations when one wants to export multiple modules without giving away an entire normal.dotm, e.g. when one wants to provide a friend with some macros etc. So the question is anyway of interest.

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.

Add VBA Project to Visio Document by Using Code

I've been asked to create a macro to update a few hundred or so Visio drawings, and keep them updated.
The update involves putting all objects of a certain type on their own layer - simple.
Now, this is easy enough to do, but when a user adds a new object some time in the future it will likely be on a default layer. So I had hoped to be able to include a VBA macro which is triggered by the Save event to re-assign objects to their layers.
The problem here is that I'd need to include this macro in every document since Visio doesn't have an application level VBA project.
Is there any way to introduce a VBA project to ALL Visio documents using code (VBA or otherwise)?? Or is there an alternative I might not have considered? Unfortunately an Add-in is not really an option due to available resources.
You have a couple options here:
Force every user to allow programmatic access to the VBA project for their documents, and use VBA automation to add code. This works nicely when you have programmatic access, but this can be difficult to assure.
If you're not using Visio 2013, you can actually save a document as VDX (xml) and replace the data for the VBA project with your own (you'd save out a document as VDX manually, and copy out the chunk of data for the VBA project). As I said, this wouldn't work with Visio 2013 since they seem to have eliminated the VDX format. You probably can get away with something similar with the VSDX XML format for 2013.
You can 'migrate' everyone's documents to a new VST file you provide. This would just involve copying and pasting all the content from a document into the new document that has your code in it. You have to be careful though to make sure all the document- and page-level data comes along, too (meaning DocumentSheet and PageSheet and any Document XML properties that may be important, and attributes like Author, Description, etc...)
Item 1 is the easiest, aside from the pain getting programmatic access to VBA Projects, unless you can have people send you documents to migrate.

VBA favourite code management

Just like Visual Studio allows us to drag our favourite code to toolbox and then use it later in any project. Do VBA allows this kind of functionality by any chance.?
What is the best way to manage the favourtie/reptitive vba code which i can use it in multiple workbooks?
In Excel you can possibly use Personal.XLSB file which could be a kind of container for all subroutines which you refer to quite often. You can create and organise them in modules, class modules. Some UserForms can be placed there as well. Each time you open Excel Personal.XLSB would be the first opened workbook then.
How to create 'Personal.XLSB' if you don't have it? Go to excel, start recording macro but before you press OK choose something like 'Personal Macro Workbook' on the second list. Do not forget to save it each time you leave Excel to keep all changes in your code.
VBA doesn't have a similar feature, no.
You can export your classes and modules to standalone files, and import them into other VBA projects. And some apps, such as Microsoft Word, have features to share macros between documents, in the case of Word by attaching those macros to the Normal template. But there is no feature to reuse small snippets of code.
Have a look at MZTools ... there are versions for VB of various flavors, and for VBA. I'm not sure if it's suitable for handling huge numbers of code snippets but for smallish amounts it should be fine. It's free and has dozens of other hugely useful features.