VB within Office Application: Is there a Sub Main()? - excel

What is the relationship between Visual Studio IDE and the Microsoft Visual Basic for Applications environment?
A colleague provided a VB script for manipulating Excel worksheets. Her script works well, and I'm using the task and her script to learn VB.
Instead of Visual Studio, her instructions have me open her Excel XLSM file and open the VB editor using Develop tab > Visual Basic button (or Alt-F11). There are three projects: ATPVBAEN.XLAM (The Analysis toolpack) which is password-locked, FUNCRES.XLAM (which contains two Sub, neither of which is named Main, and no Modules), and a project from my colleagues XSLM file, which contains one Sub, which is also not named Main. Is there a Main in the locked file, or is a Main not needed as described in Structure of a Visual Basic Program ?

Related

How to set Visual Studio to view VBA files as pure text?

I have a project which is partly written in C#/C++ and partly in Excel/VBA. I use an Excel add-in which exports all VBA code from the Excel file when I saving.
This way I can use git to store all my source code for the project in a repo.
When I open the VBA files using Team Explorer and inspect changes, all source files ending with .bas, .frm and .cls are automatically interpreted as Visual Basic .NET.
As VBA and Visual Basic are not compatible all the way, Visual Studio shows errors and suggestions for the VBA code.
How do I turn that completely off? I.e view it as pure text. Or is there any way to add VBA language editor to Visual Studio?

How can I deconstruct a VBA .xlam project into .cls and .frm files?

I'm currently developing an Excel Add-in written in VBA and using Excel with its Visual Basic editor. My problem is that Excel will compile the code into a single {Addin}.xlam file that's useless for version control and restricts me to only using the Visual Basic editor, which is difficult and awkward to use on Mac.
I'm aware of tools like Rubberduck and XlTools, but these all seem to be restricted to working only within Excel. What I'm looking for is a CLI tool with convenient functions like:
vba build src/ (constructs a workable .xlam from src files)
vba extract addin.xlam (extracts src files from .xlam)
This would be really helpful so that I can use version control as well as Visual Studio to write VBA.

VSTO Excel ribbon tab - separate code (.NET) into modules

I'm on the VBA ---> VB .NET journey and am in the process of building a custom Excel ribbon for Excel 2013/16 in Visual Studio.
When I selected the ribbon as the project, Visual Studio added a few tabs, one of which houses the code for the on-click actions for the buttons.
My background being VBA, I'm used to being able to have separate modules for different things and want to do the same (e.g. one module for calculation buttons, one module for formatting buttons, etc.) but can't see a way to have separate modules in this fashion. I tried to just create a new tab in VS but got nowhere with that...
Any ideas?
Try Project>Add new Module
by this way you can create separate module for all different calculation.
you can call this module procedure from button click event of ribbon code.
Since you are now using VS Studoi for Excel Plugin (VSTO) development, I don't think here you will find different modules for differet functions/onclick/events.
But as an alternate you can crearte partial classes here and can break your code in different files. In vb.net it will add new functions and event code in the single file only by default

Alternative to macros in Visual Studio 2012

I use macros extensively for ViewModel properties in XAML development. I use them even more in WCF to generate Message and DataContract properties.
To my disappointment, the macros I've built aren't going to be usable in Visual Studio 2012.
An example of what I'm talking about, for a VM, I would enter something like this.
int id;
string name;
Select both lines, run a macro and end up with
private int _id;
private string _name;
public int Id
{
get {return _id;}
set
{
if(_id != value)
{
_id = value;
RaisePropertyChanged("Id");
}
}
public string Name
{
if(_name != value)
{
_name = value;
RaisePropertyChanged("Name");
}
}
I'm looking for ideas of other solutions deal with losing macros.
The simplest alternative to macros is creating add-ins. I know, I know, I wasn't excited about it either, but it's actually surprisingly easy. There are three simple parts to it:
Create the macro project, stepping through a wizard UI.
Write your code.
Copy the macro's .addin and .dll files to your Visual Studio Addins directory.
Let's take a simple macro I wrote to show the Start Page after closing a solution and turn it into an add-in.
Create the macro project
Run VS 2012 and create a new project.
Go to Templates > Other Project Types > Extensibility and select Visual Studio Add-in.
Give it a name, such as ShowStartPage.
Click OK. This brings up the Add-in Wizard.
Step through the wizard, choosing:
Programming language: we'll use C#
Application host: VS 2012 should be selected
Name and description for your add-in
On the add-in options page, checkmark only the second option ("I would like my Add-in to load when the host application starts")
Skip past the About Box stuff for now, and click Finish.
Now you have an add-in project. Here's what you do with it:
Write the code
Open the Connect.cs file. (It might already be open. Some of the "DTE" stuff should look familiar.)
Add this code at class level:
SolutionEvents solutionEvents;
Add this code to the OnConnection method, right after the _addInInstance = (AddIn)addInInst; line:
solutionEvents = _applicationObject.Events.SolutionEvents;
solutionEvents.AfterClosing += () =>
{
_applicationObject.ExecuteCommand("View.StartPage");
};
Hit the "Run" button to test your code. A new instance of Visual Studio 2012 starts up, with your add-in loaded. Now test the add-in and make sure it works. (Open a solution, then close it; the Start Page should return when you do.)
Deploy it
Once the add-in works, to use it regularly with Visual Studio 2012, you only need to deploy two files:
ShowStartPage.AddIn (from your main project directory)
ShowStartPage.dll (from your project's build directory; e.g. bin\Debug or bin\Release)
Put those two files in your VS 2012 add-ins directory, probably located here:
C:\Users\[your user name]\Documents\Visual Studio 2012\Addins
Then exit and restart Visual Studio, and you should see your add-in working. You should also see it listed when you go to Tools > Add-in Manager.
While this is a bit more of a nuisance than just opening the macro editor and sticking your macro code in there, it does have the advantage that you can use any language you want, instead of being stuck with the somewhat flaky VB-like editor in past versions of Visual Studio.
The Visual Commander extension (developed by me) is an alternative to macros in Visual Studio 2012/2013/2015. You can even reuse your existing Visual Studio macros code in new VB commands.
I'll stick to cutting the text into Notepad++ and using macros there, then pasting back. It is a shame the feature isn't in Visual Studio 2012 any more...
There is an add-in, VSScript, for Visual Studio which replaces missing macros functionality. Although it does not use Visual Basic, but the Lua scripting language, you might want to try it out.
There is a recorder, macro code editor window with IntelliSense, and a simple debugger. The add-in also supports earlier versions of Visual Studio, so if you prefer the Lua language rather than Visual Basic, you can use it instead original Visual Studio macros.
I was very sad to see Macros go too. You can get close with substitutions using the regular expression search and replace inside of Visual Studio 2012. In your case:
Find:
(.*) (.*);
Replace with:
private $1 _$2;\npublic $1 $2\n{\n get {return _$2;}\n set\n {\n if(_$2 = value;\n RaisePropertyChanged("$2");\n }\n}\n
That will get you everything except capitalization of property names which Macros would be better for.
But one advantage of the regular expression approach is when the input isn't as simple (e.g. database table DDL statements).
Here are a couple of useful links from MSDN:
Substitutions in Regular Expressions
Using Regular Expressions in Visual Studio
I use Notepad++ with regular expressions like this:
Find:
public (.\*) (.)(.*) \\{ get; set; \\}
Replace:
private \1 \l(\2)\3; \r\n public \1 \2\3 \\{ get \\{ return \l(\2)\3; \\} \r\n set \\{ \l(\2)\3 = value; OnPropertyChanged\(para => this\.\2\3\); \\}\\}
Check out http://devexpress.com/coderush
The templates feature does pretty much what you want.
There is a free "Express" version too.
Visual Studio 2012's lack of macros was getting me down, as I have a few that I use literally all the time to insert standard little bits of text with a single keypress. So I wrote a very simple scripts extensibility package, VSScripts, which allows manipulation of the current selection from a command-line program.
This doesn't claim to be some all-encompassing full replacement for the old macro system, and it doesn't provide keyboard macros, but it does make it possible to recreate many types of text manipulation macro.
Here's what I did to keep my macro functionality...
Download and install the Visual Studio 2012 SDK here (it contains the "Visual Studio Package" template)
New project -> Installed.Templates.Visual C#.Extensibility.Visual Studio Package
Wizard page 1 of 7
language = C#
gen new key is fine, or use another if you have one
wizard page 3 of 7
check "menu command"
Wizard page 7 of 7
uncheck both integration and unit test project options
Click finish
In the .cs file:
using EnvDTE;
using EnvDTE80;
...
private void MenuItemCallback(object sender, EventArgs e)
{
MenuCommand cmd = sender as MenuCommand;
// This should start to look like familiar macro code...
EnvDTE80.DTE2 dte2 = Package.GetGlobalService(typeof(EnvDTE.DTE)) as DTE2;
TextSelection selection = (TextSelection)dte2.ActiveDocument.Selection;
dte2.UndoContext.Open("macro command replacement");
selection.Text = "inserted from macro replacement";
selection.NewLine(1);
dte2.UndoContext.Close();
...
Run the project. A new Visual Studio instance will start with the package loaded.
Find your command as the first entry at the top of the Tools menu. Click it to see if it works.
To install for real, go to your bin\debug(/release) directory and double-click on the .vsix file
It should be installed for the next time you run
Go to menu Tools -> Options... -> environment.keyboard and map a keystroke to your tool
Mapping theme : Visual C# 2005
Command : Tool.yourFunctionName (functions defined in the .vsct file)
If you want more than one command, you will need to add menu id's in the PkgCmdID.cs, Guids in the Guids.cs, layouts in the .vsct and a function in the *package.cs (and button(MenuCommand) in the Initialize function) for each one. It can all be done in the same project.
I used this project to create several new 'tools' with my old macro code, then mapped my keys to them. It's a lot more work (and headaches) up front, but doesn't have the lag time that macros had.
There is probably a way to do this without having it take up tool menus. I started looking at this last night and finally got it to work, so I'm done with it for now (at least until Microsoft decides to drop this too).
Personally I like this one - the Visual Commander extension lets you automate repetitive tasks in Visual Studio.

Can VBA Code Be Run Outside of MS Applications?

I just started to learn VBA. As far as I understood, one uses VBA to write macros in MS-Excel. But I wonder if it the only area of application for VBA. Can it be also used like many other standard languages - like Python, for example.
If it is the case, how can I compile a VBA program? Should it be compiled? How can I run such a VBA program?
VBA is compiled to p-code. P-code is an intermediate language that requires an additional runtime in order to execute. This runtime is hosted by most Microsoft Office applications (including various non-Microsoft applications).
In short, you cannot write a VBA only app that is compiled to an .EXE.
To create a stand-alone VBA-like program, you would need to use Visual Basic 6 or earlier. The successor of Visual Basic 6, of course, is VB.NET, which is a very different animal.
VBA can be licensed, and there are quite a few pproducts outside office that use VBA. MS no longer issues new licenses. There are non-MS VBA implementations, like from Summit software. In any case you need to have your own product that would host VBA.
A notable application supporting VBA is AutoDesk AutoCAD. It licenses the VBA runtime and has its own object model.
If you don't compile the program ahead of time (in the Visual Basic Editor click Debug -> Compile), then Microsoft Office compiles it at run time. You really should compile frequently though because that is how you find compile errors.
How you run a VBA application depends entirely on how you have set it up to run. In Excel for example you can have the Workbook_Open event start your code when the workbook is opened or create custom menus that users click on to run the code. In Access, you can set a form to display when the database opens or create an autoexec macro that will run when the database opens. etc. etc.
Like someone else said above, you can't create .exe files of VBA. The code has to run in a Microsoft Office Application.

Resources