How to run macro in already open multiple workbooks - vba

An application generates several csv files. I need to run my vba code(which may reside in a separate excel file and I can call it via a .vbs button) so that it loops through all the csv's (that are already open) and does its thing like sorting, formatting and saving as per my codes logic.

If all the workbooks are in the same instance of Excel (including the excel file with the sorting/formatting code), you can do
For Each Workbook In Application.Workbooks
'do your thing
Next
If that is not the case, you should probably make that the case. If not possible, see Can VBA Reach Across Instances of Excel?

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.

Distribute updated Excel VBA code to Multiple End-Users

I've created an Excel 2010 workbook with a number of sheets. VBA code that performs various data manipulations is in a couple of modules, and also attached to a couple of forms. The workbook is being distributed to a couple dozen people in different departments to use. They will be populating their workbook with their own department-specific data.
If I need to distribute an update to the code (either a bug fix or some new function), how can that be done? I don't want the users to have to reenter or copy/paste all their data into the 'new' workbook - I'm essentially looking for a method to update the VBA Project that's inside their existing workbook.
You could create an additional helper workbook Help.xlsm, that has its file attributes set to read-only.
Move all the vba code, that you might need to change in the future, into Help.xlsm
The file that you distribute then needs a reference adding to Help.xlsm
Now in the future changes can be made to Help.xlsm and they should appear in the client's files.
Above assumes all your customers are on the same network so that you can store Help.xlsm somewhere that is accessible to all their files.
This article explains it better than me:
http://www.excelguru.ca/content.php?152-Deploying-Add-ins-in-a-Network-Environment
You would need to export the modules and forms and manually import them into the existing workbooks. I used to have to do this for some projects i worked on.
Alternatively you would need to write some helper code to import the old data into a newly published workbook, but this depends on how the data is organised of course. Again this is another approach I took for a different project.
You can also do this procedurally. Ive used this for small patches.
http://www.cpearson.com/excel/vbe.aspx

Determine if a Word document or Excel spreadsheet has a macro included

When reading the binary of a Word or Excel document into memory, is it possible to inspect the data to determine if a macro is built into it?
If you set the security level for macros Excel (and I expect word) will ask you if you want to run a macro only if there are macros.

Is there a tactical (read 'hack') solution to avoid having the VBA code and Excel sheet as one binary file?

As I understand it when I create an Excel sheet with VBA code the VBA code is saved as binary with the sheet. I therefore can't put the code into source control in a useful way, have multiple devs working on the problems, diffing is difficult, etc.
Is there a way round this without switching to VSTO, COM addins etc? E.g. for the sheet to load all is VBA in at runtime from a web service, shared drive, etc? Any ideas appreciated.
Thanks.
I wrote a kind of build system for Excel which imports the VBA code from source files (which can then be imported into source control, diffed, etc.). It works by creating a new Excel file which contains the imported code, so it might not work in your case.
The build macro looks like this, I save it in a file called Build.xls:
Sub Build()
Dim path As String
path = "excelfiles"
Dim vbaProject As VBIDE.VBProject
Set vbaProject = ThisWorkbook.VBProject
ChDir "C:\Excel"
' Below are the files that are imported
vbaProject.VBComponents.Import (path & "\something.frm")
vbaProject.VBComponents.Import (path & "\somethingelse.frm")
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs "Output.xls"
Application.DisplayAlerts = True
Application.Quit
End Sub
Now, the VBIDE stuff means you have to import a reference called “Microsoft Visual Basic for Applications Extensibility 5.3", I think.
Of course you still have the problem with having to start Excel to build. This can be fixed with a small VB script:
currentPath = CreateObject("Scripting.FileSystemObject") _
.GetAbsolutePathName(".")
filePath = currentPath & "\" & "Build.xls"
Dim objXL
Set objXL = CreateObject("Excel.Application")
With objXL
.Workbooks.Open(filePath)
.Application.Run "Build.Build"
End With
Set objXL = Nothing
Running the above script should start the build Excel file which outputs the resulting sheet. You problably have to change some things to make it movable in the file system. Hope this helps!
I would strongly recommend against trying to load the VBA at runtime. The VBIDE automation is flaky at best and I think you'll run into quite a lot of maintenance and support headaches.
My solution to this was to export the code peridocally for source control as text files. I would also remove all code from the xls (complete removal of Forms, Modules and Class Modules and deletion of code in Worksheet and Workbook modules) and put only this 'stub' xls into source control.
A rebuild from source control would thereforce consist of taking the 'stub' xls, importing all the Forms, Class Modules and Modules and copy and pasting in all the code into the Worksheet and Workbook modules.
Whilst this was a painful process, it did allow for proper source control of code with all the usual capabilities of diffing, branching etc. Unfortunately most of it was manual. I did write an add-in which automated some of this but it was quickly hacked together solution, i.e. fairly buggy and requiring manual intervention. If I ever get round to revisiting it and getting it up to scratch then I'll let you know ;-)
Interesting question ... we also have a problem with VBA source control but have never actually got around to address it.
Does this Microsoft KB article match your criteria ? The code is put in a .BAS file which can be in an arbitary location (and separate from the .xls).
As I said I've never actually tried to do this but it looks as if this might be one approach.
The shortest path forward is using SourceTools.xla addin from http://www.codeproject.com/KB/office/SourceTools.aspx
Another approach is to write a similar tool using COM bindings to your favorite programming language. An able colleague of mine created one in Python that could export everything including VBA code, worksheet contents and formulas and even VBA references into text files and could assemble a working workbook out of those. That was prior to the XLSX format too.
I'd also advise against loading at runtime and look for a make-style utility. After all, if your code is under source control then you should only need to update your workbooks after a commit.
Unfortunately, there isn't such a utility, or at least not one that I could find.
I think compared with the alternatives (ie constantly rebuilding Excel workbook files) it'd be much less hassle to move over to VSTO or COM Addins, using VBA for light prototyping work. You also get the added benefit of not having easily "hackable" source code (ie you need more than to guess the VBA project password)

Excel save as on Run

In Excel, after writing a VBA script, I would like Excel to save the file before running it.
It is common on most of the programming tools.
While testing a program, it may crash and my program may not be saved but if it saves before each run, I won't have this problem anymore.
I know there is a automatically save option in Excel but is there another alternative ?
Add
ActiveWorkbook.Save
at the beginning of your macro