Can I skip file validation when programmatically opening a workbook? - excel

I have a roughly 100MB-large Excel file that I am opening with this code that runs when a UserForm button is pressed:
Public Sub SelectButton_Click()
fNameAndPath = Application.GetOpenFilename(Title:="Please Select a Report")
If fNameAndPath = False Then Exit Sub
End Sub
Because this file is so big, it takes a while to validate before opening, and this validation makes up about half the time my entire macro takes to complete (I'm working in Excel 2013 and this file is not opening from a network or shared drive). If I open the file manually, then I get the option to skip validation after three seconds of validating. The problem with this is that it opens the file in Protected View, where I can't work with it.
Using VBA, is there a way to "force skip" this time consuming validation while simultaneously avoiding Protected View?
When Excel is completely closed, this warning/guideline appears in the bottom left of the opening splash screen:
When Excel is already open, this warning/guideline appears in the bottom right:

So far there are two solutions that I've found to be useful for solving this problem, thanks to the comments above:
1. Disabling Office Validation for Excel files in the Registry settings for Windows:
I prefer to use early binding, so I would suggest in the VBA editor window, opening the Tools window, selecting 'References...', and then checking the box next to 'Windows Script Host Object Model', and clicking OK. This will enable IntelliSense as you are writing your VBA:
Dim wsh As New WshShell
wsh.RegWrite "HKCU\Software\Microsoft\Office\15.0\Excel\Security\FileValidate\DisableEditFromPV", 0, "REG_DWORD"
Set wsh = Nothing
This will work for Excel 2013. If you have a different version of Office or Excel, you will use something other than 15.0 in your file path.
However, this method has the glaring problem of removing validation of any Excel file on your computer, even those that might have malicious code in them or that might run from dangerous locations, such as your Temp or Downloads folder.
Additionally, writing to the Windows Registry might be disallowed depending on your current environment or permissions. For that reason, I recommend a different solution:
2. Setting the location of the Excel file to be a Trusted Location in Microsoft Excel:
It's possible to set a new Trusted Location in the Registry via VBA, but since this method is intended for use by those who can't access the registry, we won't get into that.
To add the file's location (let's say it's the "Excel Files" folder in C:\) as a Trusted Location, first click the File tab and then click Options at the bottom of the File Menu:
In the Excel Options window that opens up, click on Trust Center at the bottom of the side menu and then click the Trust Center Settings button that appears on the right:
Finally, click the Add new location... option and enter C:\Excel Files\ (or whatever your folder location is; you can even browse to it), and then click OK. You can also check the option to include subfolders if you want.

Related

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.

Opening Excel file from Sharepoint as Read-Write

I automatically open, edit, save and close several Excel workbooks from a Sharepoint location. The following code opens the workbooks (path loops through a list to hit each workbook name):
Workbooks.Open Filename:=path, ReadOnly:=False, Editable:=True
The files open in Read-Only mode, and the yellow dialogue option to Enable Editing does not appear.
I edit these workbooks manually and through a macro, but I am unable to save the files back onto the Sharepoint afterwards without saving as a new file.
I am using Excel 2013. This was working as intended about a year ago, but I believe there may have been updates to Office 365. I checked all of the Excel workbook security options, and nothing is set to open by default as Read-Only.
Is there any way to open the file in an editable mode through the macro, or at the very least allow the Enable Editing option to appear for each workbook?
I have been trying to fix the same problem for my files, and eventually did! So I felt that I could maybe let others know. And this old-ish thread came up near the top of my google search.
What fixed it for me was to edit the link.
from:
https://Company.sharepoint.com/:x:/r/teams/TeamNo/Shared%20Documents/Example/CoolFolder/TheBestExcelFile.xlsm
To:
https://Company.sharepoint.com/teams/TeamNo/Shared%20Documents/Example/CoolFolder/TheBestExcelFile.xlsm
Note that I only used replace to get rid of :x:/r/. I feel like I should have noticed this before but I didn't and no amount of meddling with the Workbook.Open parameters got me anywhere. It just seems odd that the default link copy thing gives you one with special commands in it. For our company most folders have spaces so the link has tons of "%20" in there so I simply read over the ":x:/r/".
Hope it helps someone.
Just for clarity, try this:
Sub Example()
'1.) Get filepath from somewhere
FilePath = Replace("https://Company.sharepoint.com/:x:/r/teams/TeamNo/Shared%20Documents/Example/CoolFolder/TheBestExcelFile.xlsm", ":x:/r/", "")
'2.) Open the file
Set StatisticsFile = Workbooks.Open(FileName:=FilePath, Password:="123")
'3.) Do things
'4.) Close the Sheet, save the changes. I simply like it this way, could be done in a single line.
StatisticsFile.Save
StatisticsFile.Close savechanges:=False
End Sub
I noticed this solution because I could still save the .xlsx file manually with the same name if I navigated to SaveAs. So if you guys can still do that after opening the file via macro, try a similar solution.
The interaction designed for Excel-OneDrive-SharePoint is new in 2016 apps and that version is a requisite to properly work.
The version 2013 may work by tweaking the OnDrive “Account” settings regarding Office co-authoring configuration which is specifically applied to Excel and Word
Right click the OneDrive icon in the taskbar to reach settings
Good luck!
I know your query was posted long ago but I have found the solution to remove the Read-Only blocker and update the excel document via Macro:
If you add "ActiveWorkbook.LockServerFile" after the code of opening the file, then it removes the Read-only and updates the excel as normal.

Can I compile VBA on workbook open?

I am trying to find a way of compiling the code in VBA on workbook open. I can do this manually by opening the VBA environment, going into Debug and "Compile VBAProject" but was wondering if there is a way to do this through the code every time the workbook opens.
The purpose of this is to load the code into the computers memory to prevent a compile error due to use of some Active X Objects. As mentioned, I can do this manually and it solves the problem however, as there are many users that use this and the workbook is password protected, not all will have access to the debug option.
I think you might try to do this by automating the VBE (Visual Basic Editor).
REQUIREMENT:
you need to go to Excel / File / Options / Trust Center / Trust Center settings and check the option Trust access to the VBA project object model (for security reasons this is deactivated by default, and if you don't check it the below code will raise the run-time error 1004 programmatic access to visual basic project is not trusted). Clearly, you only need to do this once (in each computer you want to execute the automated compilation, of course).
CODING:
Your command bar instruction (i.e. "Compile VBA Project") is inside the VBE object of the Excel Application, specifically in the command bars:
Dim objVBECommandBar As Object
Set objVBECommandBar = Application.VBE.CommandBars
The object will now contain the entire command bar of the Visual Basic Editor.
In particular, you look for the ID button "578", which is in fact the "Compile VBA Project" (you can put a watcher on the variable and browse all is inside into the local window, you might want to search for other commands). Hence, to summarize:
Set compileMe = objVBECommandBar.FindControl(Type:=msoControlButton, ID:=578)
compileMe.Execute
This will allow the compilation of the project. As you were asking, you just put this into the This Workbook open event:
Private Sub ThisWorkbook_Open()
Set compileMe = objVBECommandBar.FindControl(Type:=msoControlButton, ID:=578)
compileMe.Execute 'the project should hence be compiled
End Sub

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