Catch VBA Errors in VB.Net/VSTO - excel

I have search on this site and beyond for an answer to these questions, and also trawled through a collection of VB/C# books I have on VB/VSTO. So far I've drawn a blank. I've posted the same question on a VB.NET facebook group, and if I get a solution, I'll post it here so it'll help others.
I am developing an application-level Add-In for Excel using VB.Net & VSTO.
Part of the functionality involves opening .xlsm (Excel macro-enabled) files.
I have three questions I hope you can help me with.
I want to open each xlsm file with macros enabled, but not launch
any Auto_Open macro in the xlsm file, or trigger the Workbook_Open
event. Is that possible?
The xlsm file may have it's own ribbon attached to the file. Is it
possible to inhibit the xlsm's ribbon from being added?
The xlsm file may have ActiveX controls that are connected to VBA
macros. If a VBA macro produces an error, is it possible to catch
the error in the .NET Add-In? The error may include "macro not
found"
For info, at present I disable macros using the code snippet below. Whilst that helps with item #1, it doesn't help with items #2 or #3 (in fact, disabling macros is the cause of item #3).
Currently when I open the xlsm file(s) I disable macros using the following code:
' WorkbookType is a string representing a keyword within the Excel filename
' xlApp is running instance of Excel
Dim xlApp = Marshal.GetActiveObject("Excel.Application")
aWorkbook = xlApp.ActiveWorkbook
aSheet = xlApp.ActiveSheet
' Save current macro security setting
Dim oldSecurity = xlApp.AutomationSecurity
' Disable macros
xlApp.AutomationSecurity =
Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable
' Find & open WorkbookType workbook files in ProjectFolder
Dim info As New DirectoryInfo(CurrentProjectFolder)
For Each fileItem As IO.FileInfo In info.GetFiles
If fileItem.Name.Contains("~") Then
' Ignore temporary files
ElseIf fileItem.Name.Contains(WorkbookType) AndAlso fileItem.Name.Contains(".xls") Then
xlApp.AskToUpdateLinks = False
Dim wb = xlApp.Workbooks.Open(CurrentProjectFolder & "\" & fileItem.Name, UpdateLinks:=False)
xlApp.AskToUpdateLinks = True
End If
Next
' Restore macro security setting
xlApp.AutomationSecurity = oldSecurity

The xlsm file may have ActiveX controls that are connected to VBA macros. If a VBA macro produces an error, is it possible to catch the error in the .NET Add-In? The error may include "macro not found"
COM add-ins (represented by VSTO add-ins) and VBA macros are entirely different entities. You can't handle VBA errors in COM add-ins, or the opposite. But you may react to the application events, see Object model (Excel) for the list of available events.
The xlsm file may have it's own ribbon attached to the file. Is it possible to inhibit the xlsm's ribbon from being added?
To prevent the custom ribbon UI from loading you need to edit the file by removing the ribbon XML customizations contained inside the Excel file. VBA doesn't deliver any UI customizations nowadays. You can use the Open XML SDK for editing open XML documents on the fly from VSTO add-ins without involving the host application or its object model.

Related

Open Excel file in SharePoint through VBA

I'm trying to open an excel file in SharePoint through a vba code in another local excel file. However, it gives me a Dialog Box and lets me save the file instead of directly opening in Excel.
Below is the code I used. Would be very grateful for your help. Thanks.
Dim wb AS Workbook
FilePath = "https://company.sharepoint.com/sites/Folder1/Folder2/Filename.xlsm"
Set wb = Workbooks.Open(Filename:=FilePath, UpdateLinks:=0)
I had this issue also. First, you have to fix something in the excel options. So, go to File > Options > Advanced > then scroll down until you see Link Handling > then select the box that says "Open Supported hyperlinks to Office in Office Desktop Apps". Next, I used the coding below to get the link to work. you just need to reply the part of the coding with you sites url sharepoint file. the only issue I came up with is that you have to run the coding below, wait for the file to completely load, and then you can run macros on this file.
Sub OPEN_YRLY()
'
' OPEN_YRLY Macro
'
'
Range("C1").Select
ActiveWorkbook.FollowHyperlink Address:="https://aramark365-my.sharepoint.com/:x:/r/personal/......", NewWindow:=False, AddHistory:=True
End Sub

VBA Run-time error '9': Subscript out of range; trying to activate another workbook

I'm trying to create a VBA in Excel 2010 that takes info from another spreadsheet that I'm not allowed to alter and bring it over to the spreadsheet with my macro built in. Here's my code:
Sub BringUpWorkbook()
Workbooks("RITE 1624.xls").Activate
End Sub
I have several VBA books, have visited dozens of sites on the Internet, including those here at stackoverflow.com, and cannot find a reason why I'm receiving the run-time error. The workbook is already open, I've tried adding everything trailing the title, I've tried removing the .xls, I've even did all of the above with in a variable. Any ideas?
Make sure the extension is correct. If it's a excel-2010 file like you indicate, you may need to update your code to reflect the extension of your "RITE 1624" file (e.g. .xlsx for a 2010 Excel workbook, .xlsm for a 2010 Excel macro-enabled workbook, or whatever the extension is.
Sub BringUpWorkbook()
Workbooks("RITE 1624.xlsx").Activate
End Sub
EDIT:
To make sure you have the right name of the workbook, you can print the name of each workbook in an immediate window.
Open up the VBA editor, and then press Ctrl+G to open the Immediate Window (or do View > Immediate window). Then run the following Macro:
Sub OpenWkbkNames()
For Each Workbook In Workbooks
Debug.Print Workbook.Name
Next
End Sub
Note that this will give you the names of all the open workbooks in the same Excel instance as your macro. If your RITE 1624 file is in a separate Excel instance, then the instance that your macro is in will not be able to see that file (and it won't appear in the output of the OpenWkbkNames code above). The simplest way to resolve this is to open all of your necessary files from the Excel instance that contains your macro.
Sub BringUpWorkbook()
Workbooks.Open("RITE 1624.xls").Activate
End Sub

Using Excel 2010 XLAM files

I created an XLAM file which displays a customized ribbon tab, the buttons of which call various macros.
How do I get this add-in file to load automatically when opening another xlsm file?
Currently, the only way to display the add-in ribbon is to open the XLAM file first, then open the other XLSM file. Only then will the custom tab appear.
I appreciate your help.
Many thanks,
KS
In the ThisWorkbook module of the workbook (not the addin) enter something like this:
Private Sub Workbook_Activate()
Application.AddIns("MyAddin").Installed = True
End Sub
Private Sub Workbook_Deactivate()
Application.AddIns("MyAddin").Installed = False
End Sub
The word "Installed" is a bit misleading, as it only indicates whether the addin is checked or unchecked in the Addins Menu.
If by chance the ribbon is only for one workbook you should just attach the ribbon to that workbook.
If the ribbon is for multiple workbooks, people generally take the opposite approach to what you are doing, i.e., create an addin that uses application-level events to turn menus on or off when specific workbooks (or workbooks with a specific characteristics) are activated or deactivated.
If you add the file to C:\Users[user]\AppData\Roaming\Microsoft\Excel\XLSTART it will add the ribbon every time you open Excel.

Is it possible to deploy a VB application made in Excel as a stand alone app?

Basically wondering if there's a way for me to create a VB application in Excel and have it run without a full version of MS Office. The VB application would load an Excel sheet that would import a CSV onload, then print a PDF of the sheet and close.
If you have any questions, let me know.
No. Not without converting to a standalone application.
If you had were familiar with VB6 (and had access to it; it's no longer for sale), you could create a VB6 app. that references the excel COM components (still need to be installed on each target PC).
Otherwise, build an app. using VB.NET and use Office VSTO 2010 (need to reference the Office PIAs)
How to: Target Office Applications Through Primary Interop Assemblies
Just a little conflict. In office, you code with VBA, which is different than VB. What you would need to do is create a VB app that uses excel libraries or something to do some meaningful work.
The short answer is no.
You could write an external visual basic script that calls in to office and opens excel using some excel libraries, if memory serves me correctly however - you'd still require office installed on this machine. (Unfortunately I can't find a link at the moment to back this up)
Your best bet is to parse the CSV data yourself and generate a PDF from that.
There is some information here: http://www.rlmueller.net/ReadCSV.htm on how to Read CSV data using VBS (to get the examples to run, you should simply have to rename the .txt to .vbs and double click it.)
I'll leave you to find out how you'd then generate the PDF.
I don't think however this is the best solution to your problem - a full .NET application or perhaps some Python would likely serve you better.
Code will go in several different places, "ThisWorkbook" object and the "UserForm" code.
"ThisWorkbook" contains code that will determine if the UserForm is the only Excel thing (workbook) open, and if it is it will hide the Excel application and hide the workbook itself. and if other workbooks are open it simply hides the workbook. I have it set to hide the application and the workbook in both cases so that a new instance of Excel can be opened after the UserForm is running without pulling up the workbook associated with the UserForm. The code for this is below (goes into the "ThisWorkbook" object):
Private Sub WorkBook_Open()
Dim wb As Workbook
Set wb = Workbooks("MyBook.xlsm")
If Workbooks.Count > 1 Then
wb.Windows(1).Visible = False
Else
wb.Windows(1).Visible = False
Application.Visible = False
End If
UserForm1.Show vbModeless
'Put defaults and populations here
End Sub
The UserForm1.Show vbModelessallows for Excel to be used while the UserForm is active.
A couple of notes on this section:
"UserForm1" is the name of my UserForm, change this to the name of yours
Where I Set wb = Workbooks("") change inside the quotes to the name of the
workbook the UserForm is in
The IfElse statement could be eliminated and moved to the If, if you don't need any other action on the opening with no other workbooks open
The next section of code goes in the UserForm Code. I have a button set up to show the Excel workbook in order to edit it and whatnot, you could have a region you click if you don't want a button to show up. When you want to activate the Excel sheet and the application will need to be activated. I unload (deactivate) the active thing (the UserForm). This bit of code isn't necessary if the user doesn't need access to the spreadsheet:
Private Sub See_Excel_Click()
Dim wb As Workbook
Set wb = Workbooks("MyBook.xlsm")
wb.Windows(1).Visible = True
Application.Visible = True
wb.Sheets("Sheet1").Activate
Unload Me
End Sub
Within the userform there should be a way to handle what happens when the userform is closed, as the excel application and workbook will stay open hidden in the background. I have the action close the workbook and the application. A quick note, if you set the Cancel = True then the red x button won't close the userform. The code I use for this is:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = 0 Then
Cancel = False
Dim wb As Workbook
Set wb = Workbooks("MyBook.xlsm")
wb.Windows(1).Visible = True
Application.Visible = True
ThisWorkbook.Saved = True
ThisWorkbook.Activate
If Workbooks.Count > 1 Then
ActiveWorkbook.Close
Else
Application.Quit
End If
End If
End Sub
That is it for the code that goes inside the UserForm. And the code that is necessary to have the UserForm in VBA act as it's own application while allowing for Excel to operate normally at the same time as the UserForm.
To summarize what happens:
When the Workbook is launched the workbook is hidden, and if no other workbook is open the the Excel application is hidden.
The UserForm is initiated to allow for Excel to be used at the same time
When the spreadsheet is activated again excel is re-enabled and the application and un-hide the worksheet
When the user form is closed, the workbook is closed, and if there are no other workbooks the excel application is closed
If you set defaults or populate ComboBoxes put them in the "WorkBook" object code.

How to get User Defined Functions in Excel Add-Ins (Excel 2007) to work with AutoComplete?

I have created an Add-In and when I go to use it in the expressions box the autocomplete doesn't work. I do see them when I click the functions 'f' button under user defined functions. I would just like the AutoComplete to work with them so I don't have to memorize their names or have to click the functions 'f' button each time.
Although this is an old thread, there seems to be very little solutions out there. I have found an example over at JKP Application Development Services originally found by Laurent Longre. One caveat is explained below:
Disadvantage of this trick method, is that one is actually re-registering a function within the dll one uses, which might be used by any program
http://www.jkp-ads.com/Articles/RegisterUDF01.asp
This solution only registers/un-registers the UDF, but the user will still have to save the workbook as an .xlam and install the addin. I used the following code to automatically install the current workbook as an Excel addin (if you are going to be updating the addin, you'll need to add some error catching to determine if the addin is already installed).
'Saves current workbook as an .xlam file
sFile = Application.LibraryPath & "\" & "name_of_addin" & ".xlam"
ThisWorkbook.SaveAs sFile, 55
ThisWorkbook.IsAddin = True
'Adds temporary workbook
Workbooks.Add
'Installs the addin
Set oAddin = AddIns.Add(sFile , False)
oAddin.Installed = True
'Closes temporary workbook
Workbooks(Workbooks.Count).Close
MsgBox ("Installation Successful. Please close Excel and restart.")
'Closes workbook without saving
Workbooks(sFirstFile).Close False
AFAIK there is no way (unfortunately) in current Excel versions including Excel 2010 to make a UDF use Autocomplete. There are ways to add argument descriptions and help for the function wizard.

Resources