Excel save as on Run - vba

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

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.

How to run macro in already open multiple workbooks

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?

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.

Manipulate Excel workbooks programmatically

I have an Excel workbook that I want to use as a template. It has several worksheets setup, one that produces the pretty graphs and summarizes the numbers. Sheet 1 needs to be populated with data that is generated by another program. The data comes in a tab delimited file.
Currently the user imports the tab delimited file into a new Workbook, selects all and copies. Then goes to the template and pastes the data into sheet1.
This is a large amount of data, 269 columns and over 135,000 rows. It’s a cumbersome process and the users are not experienced Excel users. All they really want is the pretty graphs.
I would like to add a step after the program that generates the data to programmatically automate the process the user currently must do manually.
Can anyone suggest the best method/programming language that could accomplish this?
POI is the answer. Look at the Apache website. You can use java to read the data and place it in cells. The examples are very easy.
You can can solve this, for example, by a simple VBA macro. Just use the macro recorder to record the steps the user does manually now, this will give you something to start with (you probably will have to add a function to let the user choose the import file).
You said you have some data generated by another program. What kind of program? A program that you have developed by yourself and where you can add the excel-import functionality? Or a third party program with a GUI that cannot be automated easily?
And if you really want to create an external program for this task - choose whatever programming lanuguage you like as long as it can use COM objects. In .NET, you have the option of using VSTO, but I would only suggest that for this task if you have already some experience with that (but than you would not ask this kind of question, I think :-))
Look here:
Create Excel (.XLS and .XLSX) file from C#
There's NPOI (.NET Framework version of POI) so that you can code in C# if you want.
If you use two workbooks - one for data and one for graphs - and don't update links automatically you can use a macro to get the data (maybe an ODBC connection if the file is in a format it can read - long shot) and then link the charts to the data workbook.
Use a macro to update the links and generate the charts and then send them out and hope no one updates the links.

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)