Excel Interop fails when I open the Excel applicaion manually! Why? - excel

I have a c# application that uses Microsoft.Office.Interop.Excel. The application runs for a long period of time! If I try to open Excel manually on a different worksheet from the one the c# application is processing the c# application fails with some HResult cryptic message.
Is there a limitation with Microsoft.Office.Interop.Excel in that only 1 excel process can run at once?
Any information around this issue would be great!
thanks for any help!

Mostly, it is how your code is interacting with Excel that is the problem. Many people use ActiveCell, ActiveWorkbook, and so on. Therefore, when you open another workbook during this process, you will generate some kind of error. To avoid this, open another instance of Excel. In our shop, we created a shortcut in our "Send To..." folder. We could then just right-click on the file in Windows Explorer, select "Send To..." menu, then click on our shortcut. This saved us from having to open Excel, select file open, browse to file, and so on.

Related

VBA automatically agree to enable macros

I have a VBA code that is opening a lot of different excel files with macros. However, every time VBA opens a file, it says "Microsoft Office has identified a potential security concern", and I have to select "Enable Macros". Is there a way to add a line, that would always choose "Enable Macros", as I cannot change any excel settings (it is a corporate computer, without admin rights)?
Thank you!
Typically when opening a macro-enabled file using code, there's no security prompt. It would help to show the code you're using to open the files.
However if you do see a prompt you can fix that by setting Application.AutomationSecurity to the appropriate value
See: https://learn.microsoft.com/en-us/office/vba/api/excel.application.automationsecurity

VBA Workbooks stop working with upgrade to Excel 365 - VBA Compiling Issue?

Since upgrading to Excel 365, my company has been having all sorts of trouble with VBA-supported Excel workbooks crashing or not functioning properly. The issues have popped up in various workbooks and various departments, including seemingly simple VBA workbooks. I've discovered a fix (see below) but it's not sustainable.
The Issues
The various issues we have experienced are listed below. Note, these issues only occur when you open a file in Excel 365 desktop. The same files, when opened in the Excel 365 browser app or in Excel 2016 will work fine. Also, all these issues happen at random. A user may have been working in a file for weeks and then the next time they open the file they get one of these errors.
"Can't find project or library" errors even when we are using the standard set of libraries and basic VBA. Then when you open the VBA Editor window, all the VBA screens are essentially frozen up and the library list is inaccessible.
Excel hard crashes or locks up when opening these files and enabling VBA. Note, the crash only occurs when the VBA is enabled. If you open a file without enabling VBA, it will work fine (though obviously you can't use any of the code).
The file opens seemingly fine, but the VBA doesn't work and once again, everything is locked up when you access the VBA editor window.
"unhandled win32 exception occurred" error
when executing a command, getting an error 32809 which seems to indicate the compiled VBA has been corrupted
The Fix
Opening the VBA Editor window, then selecting Debug -> Compile VBAProject seemingly fixes the issue. I've yet to experience any of the above issues where the file had been manually compiled this way. The problem with this is that every time you add code to a file or any time you add a new tab to a file, you have to go in and perform this manual compile again.
Yes, apparently adding a single tab in a file changes the workbook structure enough that it is necessary to compile again. The Compiled VBAProject selection will be greyed out. But adding a tab (or adding new VBA) will un-grey it and require another manual compile or the problems start occurring again.
This fix also works to repair files where the above issues are occurring. To fix those files, you can:
Make sure "Disable Trusted Documents" and "Disable VBA macros with notification" are toggled on in your security settings so that VBA doesn't automatically run when you open a file.
Open the file with the errors but do not enable the VBA.
Go to the VBA Editor window, select Debug -> Compile VBAProject.
Save the file, close it, reopen it, enable the VBA, and everything works fine again.
But again, this isn't sustainable because all my users will have to remember to go compile VBA any time they add a new tab to a workbook.
Help?
Has anyone found a more sustainable fix to this issue? Is there a bug with the Excel 365 Desktop automatic compiler that Microsoft is working on?
I think I perhaps found an answer in this thread:
https://social.msdn.microsoft.com/Forums/en-US/814ac2ce-ab45-45dc-8c6a-8ef0775d189a/excel-64bit-crashes-when-activating-macros-but-excel-32bit-does-not?forum=exceldev&prof=required
Per that thread – “the cause is that Excel does not correctly save the compile state of the VBA code and 64 bit Excel cannot recover from that issue when opening the afflicted Excel file (32 bit usually can). A fix was released for only Excel 2016 and not for other versions". That would indeed confirm that it is a bug within Excel and explains why we only see the issue with 365 64 bit Excel.
That also explains why my manual compile fix works. Based on the article I found, there is a more sustainable fix. You can change Excel’s registry and force VBA to compile accurately.
To implement the permanent fix:
Open the start menu and type “reg” and select the “Registry Editor”
Navigate to: Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\16.0\Excel\options
On the Edit menu, point to New, and then click DWORD Value.
Type ForceVBALoadFromSource, and then press Enter.
In the Details pane, right-click ForceVBALoadFromSource, and then click Modify.
In the Value data box, type 1, and then click OK.

Creating custom Excel Ribbon Tab, which works in any workbook

I have surfing the net for months already and haven't really found a solution to the following task I would like to perform. Here is a deal.
I am writing a bunch of code in VBA, which basically creates a new worksheet in a workbook with a specific type of calculators (there are many) for job purposes. One sheet - one type of calculator/analysis.
What I want to accomplish is, that due to increasing amount of code - I would like to put everything on to the ribbon, so I can access a macro through that. However, the job is based on to the case-to-case analysis basis, so the each new project requires a new Excel workbook to be created, where I can choose the calculator I want and do the job.
In addition to that, it requires to be launched on all computers with Excel in the network, with ability for me to be able to modify/add a code to the macro, so that all PC's can stay up-to-date simultaneously.
To wrap-up shortly:
There is a bunch of VBA macros (which I'm constantly updating/adding);
I need to access those macros through the Ribbon in any new workbook (not the one macro are located) on a number of computers in the network;
There is a need to provide instant updates of the code for Ribbon and macro users.
SO, is there any solution, like - I create 2 files (one with Ribbon configuration, another with calculators) and drop them into the server folder? Each user access them once during the installation (basically locating the folder, where the addins are located), and if I need to modify something - I do it with those two files in the server folder and that's it.
If it's not real or pretty hard (for non-programmer) to instantly update all the users, the manual update can work out, but the minimum of being able to access the ribbon in each new workbook is a must.
Thank you in advance for help.
Thanks to all of you folks, who contributed on the question. Want to summarize the experience and provide the way I managed to go with it.
1) Get your VBA code
Let's have a code like this. It can be whatever you feel like. To do so, open VBA in the Developers tab or by pressing Alt+F11. Create a new Module, by right clicking on VBAProject > Insert > Module, name it sayMsg in the Properties window and enter the following code:
Sub saySomething()
MsgBox "What's up?"
End Sub
As I said above - this module can contain anything, usually the functional part of your code, which is going to be called out in another module later.
Let's create a new module the same way we created the first one and name it sayRibbon. This separate module contains a call function or so called "button", which runs our subroutine from sayMsg module. Copy > Paste the code below:
Private Sub sayButtons(Control As IRibbonControl)
Select Case Control.ID
Case Is = "saySomething_Btn"
Call saySomething
Case Else
End Select
End Sub
Basically, what we have here is a Case named saySomething_Btn, which is the "button" itself, with its defined call function.
Now save it as Excel Add-in file .xlam and close the program.
Notice: when you choose .xlam from a drop down menu, you will automatically be located in default Microsoft > AddIns folder. In order to save it on your Desktop, first of all choose the file type, and then relocate the folder.
2) XML map by Office RibbonX Editor
The utility above provides you with the option to create a custom tab in the Excel ribbon. Follow the link for download. All installation and use instructions are also available by that link.
After you finish with an install, open OfficeRibbonXEditor.exe file.
File > Open your .xlam file. Now it appeared in the list below.
Right click > Insert Office 2010+ CustomUI Part (or Insert Office 2007 CustomUI Part - depends on the Office version you are running).
Copy > Paste the code below:
Code
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" xmlns:Q="sayRibbon">
<ribbon startFromScratch="false">
<tabs>
<tab idQ = "Q:rxTabUI" label="Say Something" insertAfterMso="TabView">
<group idQ="Q:rxGrpUI" label="Say">
<button id="saySomething_Btn" label="Say Something" onAction="sayButtons" />
</group>
</tab>
</tabs>
</ribbon>
</customUI>
Press Validate, in case of issues - the error message will appear (Debug if needed, but you shouldn't in this case).
Now Save and Close the Ribbon Editor. You can only save, when .xlam is not opened by Excel.
3) Access the .xlam Add-In in any WorkBook
The main purpose of such approach was to provide an easy access to the VBA code from any Workbook in Excel and from any machine in the corporate network without actually installing it separately on each individual computer.
It doesn't really matter - do you want to get access only on your PC or local network, the installation process is the same.
Place .xlam file to any location of your choice (local folder or server).
Go to Excel > File > Options > Add-Ins.
Press Go... button below, Browse for the .xlam location and press OK.
Ensure the Add-In is marked in a list. Press OK.
Notice: I would recommend to encrypt your VBA for security reasons, in case if you want to be the one, who actually can edit the code - to eliminate any issues, which may arise if VBA code isn't encrypted.
I have checked the performance on my corporate network, the results are quite satisfying. All the changes you perform in the code are instantly updated among all users after they restart their Excel application.
Don't forget to release the change notes and to keep at least couple of older versions available for people, in case of need or emergency.
As long as the project will evolve, maybe more complex approaches could be used, however due to boundaries I am currently facing, this approach provides the best performance at the moment.

Why does the VBA Excel Addin code disappears and doesn't function after I close Excel and open a new Excel file?

I created a simple vba addin that colors cells based on their value, and I created a function that calls it with a shortcut then I saved it as an Excel addin and added it to Excel.
The problem is the addin works fine when I add it the first time, but when I open a new Excel file, I need to disable and enable the addin for it to work.
Update: I tried it on another computer and it works, but it shows an error that when I ignore it works fine. I am adding screenshots for the error and code
Error Message
Code
Sometimes, Excel will open workbooks in another Excel Application. This second application can sometimes face some issues with addins. You should double-check that the new file is opened in the same Excel Application. By looking at the task manager:
In this example, I'm using Window 10 and you can see that Book3.xlsx is in a different Excel Application than Book2.xlsx and Book1.xlsx
EDIT:
This question could also be of interest to you. The accepted answer reads:
This problem results from security patch in KB31152, released in July 2016. According to private communication with Microsoft software engineers:
"With this update, we changed the behavior of Excel so that it will
not load certain file types (including .xlam) when they are untrusted.
The easiest workaround is to find the add-in that is causing you
trouble, right-clicking on it in Windows Explorer, and checking
Unblock"
An easier approach is to simply place the add-in in a Trusted Location
(in Excel, go to File > Options > Trust Center > Trust Center Settings
Trusted Locations), such as the following folder, and load it from there:
C:\Users\%USER NAME%\AppData\Roaming\Microsoft\Excel\XLSTART
EDIT2:
And don't forget the option of just restarting your computer just to make sure that the problem is still there.

What is the best way to package and distribute an Excel application

I've writen an Excel-based, database reporting tool. Currentely, all the VBA code is associated with a single XLS file. The user generates the report by clicking a button on the toolbar. Unfortunately, unless the user has saved the file under another file name, all the reported data gets wiped-out.
When I have created similar tools in Word, I can put all the code in a template (.dot) file and call it from there. If I put the template file in the Office startup folder, it will launch everytime I start Word. Is there a similar way, to package and distribute my code in Excel? I've tried using Add-ins, but I didn't find a way to call the code from the application window.
Simply move your code into an Excel Addin (XLA) - this gets loaded at startup (assuming it's in the %AppData%\Microsoft\Excel\XLSTART folder) but if it's a addin, not a workbook, then only your macros and defined startup functions will be loaded.
If the functions depend on a spreadsheet itself, then you might want to use a combination of templates and addins.
I'm distributing part of an application like this, we have addins for Word, Excel and Powerpoint (XLA, PPA, DOT) and also Office 2007 'ribbon' versions (DOTM, XLAM and PPAM)
The addin startup code creates toolbar buttons if they're not found, this means in any workbook/document/etc they can simply hit the toolbar button to run our code (we have two action buttons and one button that displays a settings dialog)
Templates aren't really the way to go for VBA code, Addins are definitely the way to go...
So to load the toolbars on startup we're using something like.. (checking to see if toolbar exists though - code will run for each worksheet that is opened, but toolbars are persistent for the user session)
Public Sub Workbook_Open()
' startup code / add toolbar / load saved settings, etc.
End Sub
hope that helps :)
I always use an Add-in(xla)/Template(xlt) combination. Your add-in creates the menu (or other UI entry points) and loads templates as needed. It also write data that you want to persist to a database (Access, SQLServer, text file, or even an xls file).
The first rule is to keep your code separate from your data. Then, if you later have bug fixes or other code changes, you can send a new add-in and all of their templates and databases aren't affected.
You can modify the user's personal.xls file, stored in the excel startup directory (varies between Office versions). If you have lots of users though, that can be fiddly.
An alternative way to get over your problem is to store the macro in a template (.xlt) file. Then when the users opens it they can't save it back over the original file, but have to specify a new filename to save it as. The disadvantage of this method is that you then get multiple copies of your original code all over the place with each saved file. If you modify the original .xlt and someone reruns the old macro in a previously-saved .xls file then things can get out of step.
Have you looked into ClickOnce deploying the Excel file?
What about to save an excel to network folder with read only permissions ? The authentication can be done with integrated windows authentication and you don't need to store connection password to the database in the VBA. Then you only need distribute a link to this location to your users only once. If you will do an update, you only change data in that folder without user notice.

Resources