Insert current date in Excel template at creation - excel

I'm building an excel template (*.xlt) for a user here, and one of the things I want to do is have it insert the current date when a new document is created (ie, when they double-click the file in windows explorer). How do I do this?
Update: I should have added that I would prefer not to use any vba (macro). If that's the only option, then so be it, but I'd really like to avoid forcing my user to remember to click some 'allow macro content' button.

You could use the worksheet function =TODAY(), but obviously this would be updated to the current date whenever the workbook is recalculated.
The only other method I can think of is, as 1729 said, to code the Workbook_Open event:
Private Sub Workbook_Open()
ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = Date
End Sub
You can reduce the problem of needing the user to accept macros each time by digitaly signing the template (in VBA IDE Tools | Digital Signature...) and select a digital certificate, however, you will need to get a certificate from a commercial certification authority (see http://msdn.microsoft.com/en-us/library/ms995347.aspx). The user will need to select to always trust this certificate the first time they run the template, but thereafter, they will not be prompted again.

You can edit the default template for excel -
There is a file called Book.xlt in the XLSTART directory, normally located at C:\Program Files\Microsoft Office\Office\XLStart\
You should be able to add a macro called Workbook_Open
Private Sub Workbook_Open()
If ActiveWorkBook.Sheets(1).Range("A1") = "" Then
ActiveWorkBook.Sheets(1).Range("A1") = Now
End If
End Sub
My VBA is a little rusty, but you might find something like this works.

To avoid VBA, and if you think your users might follow instructions, you could ask them to copy the date and then paste special->values to set the date so that it won't change in future.

Related

Workbook.BeforeSave Event, Determine what Type they are saving as

I am creating a "template" which our devs have to fill out, and I want when they save it to run some custom behavior before the file is actually saved. There are two cells that are formula determined. When they user in question is saving the populated file from the template into an xlsx, I want those cells to be the values not the formulas. (This also means, I don't want the macros saved with the XLSX file either.)
A perfect example is the =TODAY() formula, which if you save a an excel file with that formula in a cell on 1 Jan 2020, when it is reopened on 1 Feb 2020, that cell will read 1 Feb 2020, not 1 Jan 2020 when it was created and saved.
Since the original file they will be opening is an xltx, it will force them to save it as an xlsx or xlsm. I want the template (xltx) to have the formulas (and macros), but when they save it as the xlsx it should only have the values.
The VB for Copy & pasting values of cells instead of forumlas is basic and I've done that many times. The problem is, when I attempt to save the tempalte as the modified template (xltx) the BeforeSave event kicks off and changes the cells back to values instead of the formulas, defeating the entire purpose. (catch-22)
Is there a way to detect that I am saving the file as a xltx or is my only recourse to put a break point in the event macro and "skip" those lines when I'm saving the template?
If you put a breakpoint in the ThisWorkbook_BeforeSave handler, you'll find that this breakpoint will be hit before the "SaveAs" UI is even displayed, and the SaveAsUI parameter will be True, and since ThisWorkbook is already saved, then its Name will include the file name and its extension.
So you can easily get the .xltx file extension, but the problem is that at that point nobody knows what the user means to be doing - namely, whether you mean to be saving the template itself, or a working copy of it: BeforeSave is fired too early for what you're trying to do.
You need to somehow have the meta-information already at your disposal.
If you are only ever a developer and aren't going to ever be saving the template as anything other than as a template file, then you can leverage environment variables - are computers given a name in your organization?
If Environ$("COMPUTERNAME") = "Your computer's name" Then Exit Sub
'...rest of the BeforeSave handler...
That gives you a way to run logic conditional to the COMPUTERNAME or USERNAME OS environment variable values.
Use a class variable to record when the SaveAs dialog has been called and then use the Workbook_AfterSave event to make the adjustments.
Workbook.BeforeSave event (Excel)
SaveAsUI: True if the Save As dialog box is displayed due to changes made that need to be saved in the workbook.
Private hasSaveAsUI As Boolean
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Rem Check to see if the file has been saved as
If hasSaveAsUI Then
hasSaveAsUI = False
Rem Do Something
End If
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
hasSaveAsUI = SaveAsUI
End Sub

Workbook_Open() in Excel 2016 not firing

Excel 2016 (or 365) does not seem to fire the Workbook_Open() sub reliably or more precisely, not at all!
The simple event sub
Private Sub Workbook_Open()
MsgBox "Work book is open"
End Sub
does not seem to work. However, if a workbook is already open and then the workbook containing the above Sub is then opened, it does run as expected.
I notice that unlike Excel 2010, 2016 (365) opens each workbook in its own window, not a workbook window in the Excel application window. Is this a bug in 2016 and is there a workaround?
I have produced a work around for my own applications and that is call the activation of a worksheet and call my initialization routines from there. But a bit "rough" and it would be good to have the Workbook_Open() sub working correctly.
It is a simple single Sub in the ThisWorkbook module. Macros are enabled. In Excel 2010 it works perfectly, as do two other macros in other workbooks for which I have written macros. It is just this one thing with Excel 2016. Given that the Workbook_Open() sub is the gateway to a workbook it seems a little strange that we have to go to a workaround to make it function.
Try encapsulating the call with a new instance of Excel. Example below:
Sub OpenInNewExcel()
Dim Background_Excel As Excel.Application
Dim pathName As String
Dim fileName As String
Let pathName = "Enter your path here" 'include "\" at the end
Let fileName = "Enter your file name here"
Background_Excel.Workbooks.Open fileName:=pathName & fileName
Background_Excel.Parent.Quit ' This is how you close the file completely using VBA otherwise the file will close and the Excel Shell will remain.
End Sub
Also make sure that enable macros is turned on in the Options-Trust Center.
You have to add the file/folder location of your workbook as a "Trusted Location".
You can see more info about that in Designate trusted locations for files in Office 2016.
I have same problem then I found solution after google it:
https://www.myonlinetraininghub.com/excel-forum/vba-macros/excel-2016-workbook_open-event-doesnt-trigger
Then I also use "Private Sub Workbook_Open()" and "Public Sub Auto_Open()" open in excel 2016 that work fine:
Private Sub Workbook_Open()
CustomStartUp
End Sub
Public Sub Auto_Open()
CustomStartUp
End Sub
Private Sub CustomStartUp()
MsgBox "Work book is open"
End Sub
I've had this problem (I'm using Microsoft 365), and I found this thread.
It happens for me sometimes when I have another workbook already open, then, on trying to open my macro-enabled workbook, before any sheet is displayed I get the Microsoft warning message about macros. Then, although I click its 'Enable' button, the Workbook opens, macros do get enabled, but Workbook_Open doesn't run.
I've never known the problem to occur if no other workbook is open. (Of course, the user might still get the yellow-backed messages at the top of the workbook, asking them to click the Enable Editing and/or Enable Macros buttons.)
Note that my Workbook_Open just calls another 'workbook-opening' sub in a module to do all the opening processing.
My solution: When my workbook-opening sub is called, it sets a global variable to True to indicate it has run.
I've made it obvious to the user that the problem has occurred, by means of a 'Welcome' sheet with all its cells locked, so the user can do nothing; at this point all other sheets are very hidden. The workbook-opening sub, when it runs, deactivates this sheet and makes it very hidden, so the user never normally sees it, and makes the other sheets visible. But if this screen remains, it instructs the user to select the other workbook, then select this one again. My Workbook_Activate code then runs, and because the global variable isn't True, it calls the workbook-opening sub. If this global variable is True, it does nothing.
To make this work, the Workbook_Close sub makes the other sheets very hidden and the Welcome sheet visible, ready for the next time the Workbook is opened.
Hey presto, the problem is solved.
The Welcome sheet actually has a dual purpose, in that if either of the yellow-backed warning messages are displayed, it will remain and force the user, with suitable instructions, to click Enable Editing and/or Enable macros. If the users aren't au fait with macro-enabled Excel, they will just ignore these and try to carry on regardless.
All this is much easier to implement than to explain. I hope it's clear.
And I hope this might be of help to someone.
I had this issue with one of my files as well. I managed to fix this issue by running Workbook_Open manually in the VBA editor once open and saving the file in another location. The file in the new location should have no issue with auto-running Workbook_Open. If this doesn't work, copy the original file to a new location before manually running & saving.
If the newly saved file does not run Workbook_Open, repair your version of Office.

Enabling macro by default on a workbook

I am new to VBA/Excel programming, I am refreshing a pivot table using a macro. I have the following VBA code on one of my sheets.
Excel version : 2013 ( saving my file as macro enabled workbook)
Private Sub Worksheet_Activate()
RefreshPivotTables
End Sub
Private Sub Worksheet_Deactivate()
RefreshPivotTables
End Sub
The code works fine when I switch back and forth after enabling the macro, but when I open the Excel doc I get this "Enable macro ribbon" at the top which is preventing the macro from running. I need to switch to another tab and come back to my original sheet to activate the macro.
Is there a way to set "Enable Macro" for the workbook by default / some code that will do this on behalf of the running user? I cannot expect all my users to switch workbooks and come back to see the refresh happen.
Go into the options in Excel and then to the trust center settings. Put the location in as a trusted location.
Alternatively on my machine if I open a sheet, enable macros then close it again a few times Excel asks if I want to make this a trusted document.

automatically run excel macro upon creation from template

I want to create an excel template that will includes formulas for dating the columns. However, since those formulas will be based on TODAY(), I need to convert them to static strings (so the dates don't change everytime someone opens it). Is there a way to add a macro that will run automatically when someone creates a new spreadsheet based on the template? (Similarly to Auto_Open(), only on Create, rather than Open). If so, I could just create a macro that will replace the formulas with their results upon document creation. Can this be done?
[Note: I'm not married to this solution; it just seemed like the simplest way to protect my spreadsheet. If someone can suggest an alternative approach, I'd be obliged.]
I have a couple thoughts...
If you run a copy/paste values macro every time it really won't matter, right?
You could check if the file exists yet (has been saved), and if not
then this must be the template opened as a new workbook, maybe?
Code:
Private Sub Workbook_Open()
If Dir(ActiveWorkbook.Name) = "" Then
'run the macro?
MsgBox "I'm gonna run this macro"
End If
End Sub
You could have a cell on one of the sheets, that will never be used,
or is hidden, that will store whether or not to run the macro, and
change that when the file is opened or when the macro is ran. Then
have a macro run on open that checks that cell. (Or custom/document property)
You could populate the cells that have the today() formula only on
open and if they are already populated then don't run the macro?
I realized that there is no need for a Workbook_Create() function, as that behavior can be emulated by simply deleting the macro after it has run once (which happens when it is first created). Deleting macros is done automatically when the file is saved with a .xlsx extension. In addition, you need to prevent the macro from running when you open the template itself (while editing the it). You can hold the SHIFT key when opening it to prevent auto-run macros, but since that method isn't foolproof, I added this code at the top:
Private Sub Workbook_Open()
'If we're opening the template, don't run the macro
If Application.ActiveWorkbook.FileFormat = xlOpenXMLTemplateMacroEnabled Then
Exit Sub
End If
...
'add code here to SaveAs .xlsx, thus removing the macros, so it won't run every time.
End Sub
(Note: I didn't show my SaveAs code as it is rather messy: I wanted to suppress the default warning about losing macros, but wanted to also protect the user from inadvertantly overwriting previous file. If anyone is interested, I could post it)

Installing a VBA macro in Excel 2007

I've got a VBA macro in an Excel 2003 spreadsheet and I'd like to 'install' it on a machine running Excel.
I created a 'Trusted Location' on the local machine, and I know how to copy the module to the existing workbook and assign a key combination to invoke it, but I don't know how to make the macro appear automatically when someone starts Excel. Help?
The simplest solution is ( both for xl2003 and xl2007 ) to copy your xls containing the macro to the path = Application.StartupPath from your client machine ( can build a simple vbscript installer which instantiates excel and retrieves this information ).
This way your macro will be available in any workbook opened since the xls files located in startuppath are loaded at excel startup.
I remember the old way was to save your macro in your Personal.xls
workbook - then it would be accessible
any time you opened Excel - has this changed for 2007?
That was a way. A better way was (and is) to create an Add-in, which you can then enable & disable via Tools->Add-ins. (An Add-in will remain enabled even if you close and re-start Excel). You can save any .XLS file as an Add-in (.XLA).
Within your Add-in you could just use an Auto_Open method:
Private Sub Auto_Open()
DoStuff
End Sub
...or, you could hook up the Workbook_Open event, as Ryan suggests.
Of course, since the user can disable the Add-in, you also want to do the reverse in Auto_Close (or in the Workbook_BeforeClose event).
Actually, if you use events it'd be better to use the Workbook_AddinInstall and Workbook_AddinUninstall events. Using those is slightly more "correct", and also has the benefit that the 'close' event doesn't fire if you close Excel and then hit Cancel when prompted to save.
I'm not sure what you mean by 'appear', but you can execute it automatically by calling it from
Private Sub Workbook_Open()
End Sub
in the ThisWorkbook object module. Is that what you're looking for?
I remember the old way was to save your macro in your Personal.xls workbook - then it would be accessible any time you opened Excel - has this changed for 2007?

Resources