How to completely disable macros in the Excel 2013 C# Api - c#

I have an application that uses Excel 2013. I need a way to disable all macros. I can not do it on workbook open because I do not have access to the open methods, the workbook is opened by another COM application then passed to me. It needs to happen prior to opening the document. What I am ultimately trying to do is set the setting found in the image below.

The best solution I found was to edit the registry. Shout out to Tim Williams for pointing me in the right direction
The key that needs to be edited is
HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Excel\Security\VBAWarnings
In my case I was to disable all macros by setting the value to 4
More info can be found Here

Related

Outlook Addin Installation and Deployment(userwise and machinewise)

We have developed a Outlook Add In. I wish to deploy this add in in both Single User / Multi user environment
I have managed to deploy this Add In for single user environment. I am adding a Registry Entry (HKCU) for single user and the add in gets installed under "APPDATA\ROAMING\CompanyName\AddInName." I am using standard MSI for installation
But the issue I face is even if i ran the Installer, I don't see Add In appearing under Outlook, unless, I browse to the installation path (as above) and double click on VSTO file and deploy it again.
For Terminal Server / Citrix based implementation, I am trying to change the Registry to HKLM but not 100% sure how this will work.
My question is that
1. How I can have deploy this Outlook Add in only in one attempt. I don't want to install and then deploy (double click VSTO) file?
2. How I can deploy this add in for Terminal Server / Citrix based implementation?
I have gone through various blogs but they are not very clear and cause more confusion.
Would appreciate your expert suggestions
Thanks
Unfortunately I can only answer the first part of your question - You will have to create registry entries so that when Outlook is started it automatically applies your installed add in. See the link below for a detailed explanation of the registry keys that are required. https://msdn.microsoft.com/en-us/library/bb386106.aspx
In short, You need to add a registry entry for your add in that contains a FriendlyName, Description, LoadBehavior and Manifest input. Directing to the following link will tell you exactly how to do this and exactly where to put the keys. https://msdn.microsoft.com/en-us/library/cc442767.aspx#To-create-registry-keys
Best of luck and If you have any issues with that, comment below and I will help you as soon as I can.
**As an added note, I once had problems similar to the one you are having, and in my case it was due to the LoadBehavior setting. I was using the "UK Spelling" of the word instead of the US spelling. LoadBehavior must be specified exactly as I have written it here.

Writing and Executing VBA Macros on Excel without using Excel.Interop [duplicate]

This question already has answers here:
How to inject VBA code into Excel .xlsm without using Interop?
(2 answers)
Closed 7 years ago.
Scope:
I am generating automated reports using excel, but since we have restrictions on our server, we can't install Excel.Interop or use any COM object to perform such action.
We have been using EPPLUS as our main helper on this task but it has some serious restrictions when it comes to more intricated things such as PivotCharts and Macros.
We have just finished the project, missing only the PivotCharts since EPPLUS has no support for them.
Question:
How can we :
A) Write Macros to a .xlsm file? (We could write one named "Auto_Open" so that excel would run it uppon opening, creating the charts and stuff)
OR
B) Run a macro within our code to generate those charts after putting all the needed data there?
Not using Excel.Interop is a must at this moment. We are open for some suggestions such as
SpreadsheetGear and EasyXLS, but we can't find any sample or piece of code that actually shows how to Write or Run macros.
Thanks in advance
I realise this question is a bit old, but in the interest of helping future visitors I'll add that the current version of EPPlus (4.0.4 at time of writing) supports the inclusion of VBA.
Where excelDoc is your ExcelPackage, you can drop it in using something along the lines of:
excelDoc.Workbook.CreateVBAProject();
StringBuilder vbaCode = new StringBuilder();
vbaCode.AppendLine("Private Sub Workbook_Open()");
vbaCode.AppendLine(" Application.DisplayFormulaBar = False");
vbaCode.AppendLine("End Sub");
excelDoc.Workbook.CodeModule.Code = vbaCode.ToString();
Hope this helps.
Open Excel
Press Alt+F11
You will now be in the VBA IDE.
To run something on Auto Open:
Select ThisWorkbook From the VBAProject in Project Explorer on the Left of your screen
There are Two drop downs near the top of the window one will say (General) and The other (Declarations) click on (General) and select workbook
Excel should automatically bring you to the Open declaration.
Anything written in this sub will execute on open.
Rather than attempting to programatically write macros to an xlsm file, why don't you create a template that already contains the macros you want. Then generate your reports from this template.
When a user opens the report (and allows macros to run), then your macro will run and do the manipultations you want (your option A). Your Auto_Open macro could check some suitable condition (e.g. presence of a value in a specific location, perhaps on a VeryHidden sheet so the user can't easily interfere with it) before doing any work, so that it doesn't run when you open an "empty" template.
As for your option B (run the macro before providing the report to the user): this isn't feasible without Excel Automation.

C# when opening a .xls file in the web browser it opens an instance of excel

For my C# forms application I've seen multiple tutorials saying that it's possible to open an excel file within a web browser with the following code:
this.webBrowser2.Navigate("filename", false);
http://www.codeproject.com/Articles/15760/How-to-Integrate-Excel-in-a-Windows-Form-Applicati
However, when I try this, the web browser says "Navigation to the webpage was canceled" and Excel opens with the spreadsheet open in it.
Does anyone know how to stop this happening?
Cheers,
Tom
Edit:
I have solved this now - I will post the answer in seven hours (as users with under ten posts cannot answer their own question within the first eight hours of posting it)
I've solved it!!
This problem is nothing to do with C# or Visual Studio, it's to do with how windows manages it's file types (I think).
This link tells you how to stop Excel files opening in Internet Explorer, so I just did the opposite to what they've said. (I did the registry edit method - method 2).
http://support.microsoft.com/kb/162059#LetMeFixItMyselfAlways
To solve this problem:
Go to HKEY_LOCAL_MACHINE/Software/Classes and change the BrowserFlags data number to 1 for the following keys:
Excel.Sheet.8
Excel.Sheet.12
Excel.SheetBinaryMacroEnabled.12
Excel.SheetMacroEnabled.12
Then you're done.
This has worked for .xls files and .xlsx files and their related macro files for me.
Hopefully this will help someone in the future.
Cheers,
Tom

Better option for hosting MS Office documents in custom app?

I am currently hosting an IE Browser control in a .NET (2.0) Form and using it to load Office files such as Excel and Word thusly:
_ieCtrl.Navigate("C:\\test.xls", False);
The hosting and loading works well except whenever I navigate to a file I am presented with a dialog that asks whether I want to save or open the file. (This is standard IE file-download behavior.) I always want to open it of course and I do not want the dialog to show.
Another issue is that when I close the window that hosts the IE control and the Office doc the document does not close and remains open on disk. This means that subsequent attempts to open the same file via my app or the native office app will fail because of the sharing violation.
Is there a programmatic way of avoiding this dialog and cleaning up resources afterward? I am asking for a programmatic answer because web research has only yielded solutions that entail modifying OS-level settings.
Bounty NOTE:
I am open to any solution to this issue that will allow me to:
Host an Excel spreadsheet inside my application
Work rather transparently (avoid usability issues like the one described above)
Avoid having to make any OS-specific changes that may affect other applications (especially icluding IE)
Is zero additional cost (no licensed 3rd party libs please) Code Project and other open source resources are OK
Not mess around with the DSO Framer ActiveX control, unless a stable version is developed/discovered
Is your intention for the user to be able to work with the Excel file in an Excel-ish way (i.e. columns, rows, formulas, etc.), possibly saving it back? If this is the case, I can't see how you can solve this problem well without relying on COM Interop with the Excel object model or by integrating third-party libraries to work with the Excel sheet. I know you said no paid solutions, but there are some feature-rich 3rd-party controls out there just for working with Excel files within applications.
I noticed in your comment to SLaks that the final product is a "dashboard of sorts". If your intention is to design a a custom dashboard application, have you considered parsing the Excel file(s) to extract the data and then presenting it in a logical manner within your application. This removes the need to directly display and work with the Excel file while still allowing you to work with the data inside that file. If you are trying to get the data outside of the file, here are two approaches among many:
You might consider using the Excel object model and COM interop to read the data from the Excel file into your application. Granted, this includes a dependency on Excel being installed, but it is a possibility. This article has some great code for getting started with reading Excel files in this way.
A better way might be to use a library that doesn't have a dependency on Excel being installed on the local system. This answer suggests using the Excel Data Reader library, available on CodePlex.
I know this answer side-steps your original answer of "hosting MS Office documents in [a] custom app," but in case what you're really interested in is the data inside those Excel files, hopefully this answer will prove helpful.
This is a horrible hack and should only be considered as a last resort: SendKeys.Send("{O}");
http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys%28VS.71%29.aspx
Something similar to
_ieCtrl.Navigate("C:\\test.xls", False);
(code to sleep or wait may be needed here)
SendKeys.Send("{O}");
Basically, you send the "o" key to the dialog so it presses the "open" option. You are simulating a keyboard presses to click the "open" button. It is hackey because
1) you may need to wait in between
calls. If you send the o key before
the dialog is up it will be missed.
Hopefully the navigate call is finished when the dialog pops (dont know behavior of control in c#). You may need to experiment with the time since different computers will open faster\slower
2) If the dialog is not shown on a
computer, you will be inserting "o"s
into it. This may cause problems when
exiting because it may popup another dialog to try and save
the changes. May be able to prevent this by opening it in read-only mode
3) Different versions or windows may need different sendkeys commands. For example, you may need to send "o" and them the "{enter}" key
4) Probably more :)
If you want to open the file in a separate Excel instance (not embedded in the WebBrowser control), you can simply call
Process.Start(#"C:\Test.xls");
Office was never meant to run in embedded mode, not in a web page or in an ActiveX Document host. Microsoft had time and time again given us the warning. From pulling dsoframer from the knowledge base to skipping the BrowserFlags registry key in Office 2007.
Move to Office add-ins, Excel Web Access or Office Web Apps as quickly as you can.

Programmatically configuring MS-Word's Trust Center settings using C#

I have developed a simple C# Winforms application that loads MS-Word 2007 documents via COM automation.
This is all very simple and straight forward, however depending on the document I need to programamtically Enable or Disable Macros as well as ActiveX controls.
There is probably a way to store this in the registry, but I want to control these settings on an instance by instance basis as multiple concurrent requests may be running at a time.
So my question is 'how do I configure the trust center settings using COM automation'.
I have Googled for hours, but all I have been able to find is the Application.AutomationSecurity property, but this only accepts the following values:
MsoAutomationSecurity.msoAutomationSecurityLow
MsoAutomationSecurity.msoAutomationSecurityForceDisable
MsoAutomationSecurity.msoAutomationSecurityByUI
The Word 2007 Trust Center however exposes the following settings:
Macro Settings:
Disable all macros without notification (matches msoAutomationSecurityForceDisable)
Disable all macros with notifications (I don't need this one)
Disable all macros except digitally signed macros (No equivalent)
Enable all macros (matches msoAutomationSecurityLow)
(source: visguy.com)
ActiveX controls (configured separately, I have not found any way to control these, note that according to the screenshot these settings are shared between all applications)
Disable all controls without notification
Prompt me before enabling UFI controls....
Prompt me before enabling all controls with minimal erstrictions
Enable all controls without restrictions
I have tried the old trick of recording an MS-Word macro while changing these settings, but none of these steps are recorded.
Update:
I have found the following entries for the ActiveX controls settings in the registry. Looks like ActiveX settings are indeed global and cannot be specified for a single MS-Word instance unless someone proves me wrong.
ActiveX Disabled
[HKEY_CURRENT_USER\Software\Microsoft\Office\Common\Security]
"DisableAllActiveX"=dword:00000001
"UFIControls"=dword:00000002
ActiveX Enabled with safe mode
[HKEY_CURRENT_USER\Software\Microsoft\Office\Common\Security]
"DisableAllActiveX"=dword:00000000
"UFIControls"=dword:00000002
ActiveX Enabled without safe mode
[HKEY_CURRENT_USER\Software\Microsoft\Office\Common\Security]
"DisableAllActiveX"=dword:00000000
"UFIControls"=dword:00000001
Still keen to resolve the macro settings problem
Looks like I am going to answer my own question.
I have tested it and can confirm the mappings are as follows:
Macro Settings:
msoAutomationSecurityForceDisable = Disable all macros without
notification
msoAutomationSecurityByUI = Disable all macros except digitally
signed macros
msoAutomationSecurityLow = Enable all macros
To the best of my knowledge the global ActiveX settings can only be configured by directly editing the registry
ActiveX Disabled
[HKEY_CURRENT_USER\Software\Microsoft\Office\Common\Security] "DisableAllActiveX"=dword:00000001 "UFIControls"=dword:00000002
ActiveX Enabled with safe mode
[HKEY_CURRENT_USER\Software\Microsoft\Office\Common\Security] "DisableAllActiveX"=dword:00000000 "UFIControls"=dword:00000002
ActiveX Enabled without safe mode
[HKEY_CURRENT_USER\Software\Microsoft\Office\Common\Security] "DisableAllActiveX"=dword:00000000 "UFIControls"=dword:00000001
I have left a comment in the relevant section of the MSDN website
I know this thread is quite old, but I had to figure it out today so after a quick research I found this registry for the Trust Center Settings:
This applies to Word version 2010 (and probably 2007, but with 12.0 instead of 14.0)
Or in text:
Registry location:
HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Word\Security
Macro Settings:
Name: VBAWarnings
Data:
Disable all macros without notification - 4
Disable all macros with notification - 2
Disable all macros except digitally signed macros - 3
Enable all macros (...) - 1
Developer Macro Settings:
Name: AccessVBOM
Data:
Unchecked - 0
Checked - 1
For the setting for ActiveX controls in office 2010
to DisbaleActiveX without safe mode you only need ...
"HKEY_CURRENT_USER\Software\Microsoft\Office\Common\Security" /v UFIControls /t REG_DWORD /D 1 /F
I've spent a couple of days trying the same thing and finally discovered a very simple way of opening an .xls file containing macros, without messing with the registry or Excel's trust settings. In C#:
Application aXL = new Application();
aXL.FileValidation =
Microsoft.Office.Core.MsoFileValidationMode.msoFileValidationSkip;
try {
Workbook aBook = aXL.Workbooks.Open("K:\\Work\\ExcelTest\\BrokenMacro.xls"
, 0
, true
, Type.Missing
, Type.Missing
, Type.Missing
, true
, Type.Missing
, Type.Missing
, false
, false
, Type.Missing
, false
, false
, Type.Missing
/*,false*/);
}
catch (Exception e) {
Console.WriteLine(e);
}
See MSDN for details.
My Excel trust center setting were all set to default values - "Disable All Macros with Warnings", and "Do Not trust access to the VBA object model. Without the msoFileValidationSkip option an exception was thrown. With the msoFileValidationSkip option the file opened fine.
It seems to me that this is the way to go, since it allows a program to open files with macros, but doesn't open up the Excel application virus ridden spreadsheets.
Note that I'm running Office 2010. I don't know on which version of Office this option was introduced.

Categories