I have a question on the macro events here. Below is my code. This performs the below Operations’
Private Sub SaveAsTabDelimited(ByVal sFileName As String)
With ActiveWorkbook
.SaveAs Filename:=sFileName, FileFormat:=xlText, CreateBackup:=True
End With
End Sub
Public Sub test()
SaveAsTabDelimited "C:\Users\te160772\Desktop\Toad Test\Testsanthu.txt"
ActiveWorkbook.Close savechanges:=True
End Sub
It converts the excel file into tab delimited txt file
It creates a backup copy of the excel file
I wanted this action to be performed each day inorder the excel file to upload to Oracle tables on daily basis. The reason behind converting excel spreadsheet to tab delimited txt file is to preserve the format (To prevent the removal of leading zeros while exporting it to oracle)
But now I am trying to enhance this code so that the following actions should be performed without any glitch. I have tried to do this in all the possible ways .since I am very new to the programming I was not able to do this.
The code should convert the excel file to tab delimited save on my desktop (Hope that my current piece of code is sufficient for this action)
It should create a backup copy in a folder called “Repository” (A folder in a desktop). Each change to my workbook should result a backup copy with the version history if possible(Date and Time stamp in the file name)
the biggest problem associated with my code is that upon close, three separate dialogue boxes appear - one asking me if i want to save, the other asking me if i want to keep what i have copied in the clipboard, another one is replace the existing text file saved in the folder is there a way of answering these dialogue boxes (or suppressing them) from within the macro, so i do not need to manually click on yes or no each time the macro is run?
I have attached my macro to a “shape” in excel but my priority is to run my macro upon closing of my workbook. Every time when any changes happen to my workbook and when I save the workbook, it should create a tab delimited Text files which should replace the existing Txt File without any confirmation dialogue boxes.
Please help me on this. This is badly require for me
With a million thanks
The code should convert the excel file to tab delimited save on my desktop (Hope that my current piece of code is sufficient for this action)
Yes, either you can hardcode the path to the desktop or use this code to get the path to the desktop automatically
Sub GetDesktopPath()
Dim oWS As Object
Dim DskTopPath As String
Set oWS = CreateObject("WScript.Shell")
DskTopPath = oWS.SpecialFolders("Desktop")
Debug.Print DskTopPath
Set oWS = Nothing
End Sub
It should create a backup copy in a folder called “Repository” (A folder in a desktop). Each change to my workbook should result a backup copy with the version history if possible(Date and Time stamp in the file name)
You can use the Workbook_BeforeSave event to create a copy of the existing workbook.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
End Sub
You may want to explore ThisWorkbook.SaveCopyAs See Excel Help for more info.
the biggest problem associated with my code is that upon close, three separate dialogue boxes appear - one asking me if i want to save, the other asking me if i want to keep what i have copied in the clipboard, another one is replace the existing text file saved in the folder is there a way of answering these dialogue boxes (or suppressing them) from within the macro, so i do not need to manually click on yes or no each time the macro is run?
You can get rid of these alerts by simply sandwiching your code between
Application.DisplayAlerts = False
'~~> Your Code
Application.DisplayAlerts = True
If you are using clipboard a lot, then you might also want to clear it by using
Application.CutCopyMode = False
I have attached my macro to a “shape” in excel but my priority is to run my macro upon closing of my workbook. Every time when any changes happen to my workbook and when I save the workbook, it should create a tab delimited Text files which should replace the existing Txt File without any confirmation dialogue boxes.
You can use the Workbook_BeforeClose event to run your relevant code
Private Sub Workbook_BeforeClose(Cancel As Boolean)
End Sub
Regarding the alert, I have already explained that in the previous section.
Hope this sets you in the right path.
Related
I would like to;
obtain a list of files from a specific source folder (e.g. D:\My Drive\EM SSC\PA\AttNew)
open the first source file (all Excel files, all the exact same format)
run a macro that copies certain fields from the opened file into a data table (I already have this working for a single (named) file) on a different Excel file (C:\Users\r5\Documents\DataFile_v1.xlsx)
close the source file (an ideally delete it or move it to a different folder)
open the next source file from the list
continue until all source files are dealt with
save the data table file
New Excel source files are automatically copied into the source folder each day, so I need to open each source file, copy data to my table and then remove the files, ready for the next days files.
I have only been able to complete the steps related to copying the data fields from a single source file to the data table. I am unsure of how to do the iterative part to open one file after another. I am not an experienced VBA user. I need to open a source file, copy data from it to my table, then close/delete the source file and move on to the next source file.
Use Task Scheduler to run a bat file that runs a .vbs to open and runs macros in your excel file. Explanation and example here
The bat file will contain something along the lines of
"D:\My Drive\EM SSC\PA\AttNew\Automation.vbs"
The .vbs file would be something along the lines of
Set xlsxApp = CreateObject("Excel.Application")
xlsxApp.Visible = True
Set xlsxWorkbook = xlsxApp.Workbooks.Open("D:\My Drive\EM SSC\PA\AttNew\AutomationProject.xlsm")
xlsxApp.Run("Macro1") 'Name of your macro
Closing your workbook would contain something like this, in your ThisWorkbook VBA editor
Private Sub Workbook_BeforeClose(Cancel As Boolean) 'Closes all other
worksheets par "MainSheet", saves user time not having to delete
imported sheets everytime
For Each ws In ThisWorkbook.Worksheets
Application.DisplayAlerts = False
If ws.Name <> "MainSheet" Then 'If a worksheet is not named "MainSheet" it gets deleted
ws.Delete
End If
Next ws
Application.DisplayAlerts = True
MsgBox ("All sheets are deleted except specific sheet - After this, you
can click either 'Save' or 'Don't Save' button") 'Message box to reasure user is okay with either option when closing the file
End Sub
I am not sure about next stages, but let me know how this works so far
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
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.
In Excel 2013: macro was working fine until today. Now, I can open the "Personal.xlsb" file, but I cannot use the Macro view button anymore, all I get is Excel in unresponding mode; and then, only way is to stop Excel entirely. When I go in design mode, I cannot access the macro registry at all (trying to do so results in the same unresponding state). I rebooted the PC entirely, did not help.
Pb seems specific to one specific "Personal.xlsb" file (I replaced the incriminated file with another "Personal" file in the XSTART folder and Excel macros worked just fine with a different .xlsb file). So I am suspecting a file corruption pb. If that is the case, is it possible to recover the original macros, or at least crack the macro file open and get a copy of the original coding?
You can try to get back your code if you manage to open the workbook from a macro in another workbook. Give this a shot:
create a folder where you will get the recovered code modules. Let's say "C:\myRecoveredCode". Put in a copy of your corrupt file "Personal.xlsb"
In Excel Options, Trust Center Settings, Check Trust Access to the VBA project object module
create a fresh workbook, copy/paste and run the following macro:
Sub TryRecovery()
myFolder = "C:\myRecoveredCode\"
Set wb = CreateObject(myFolder & "Personal.xlsb")
For Each comp In wb.VBProject.VBComponents
comp.Export myFolder & comp.Name
Next
wb.Close False
End Sub
If all goes well, you will have files a set of files that you can edit, or import to another workbook.
I have researched like mad about this, and I'm worried there isn't an answer. But maybe the really smart people on this site can help.
I have two workbooks that work together - Charts.xlsm and Data.xlsm. They are always kept together in the same folder. The Charts.xlsm obviously contains all of my charts, but they are all linked to tables in Data.xlsm for their source. I also have lots of slicers in my Charts.xlsm that are connected to the charts, and they share caches when they are connected to charts with the same data source. The two workbooks are always open at the same time so that the data source reference looks like this: 'Data.xlsm'!Table1
This all works great, until I put these workbooks on another computer (which is why I am doing this so I need to find out how to fix this).
Once the workbooks are closed, the source data references change to a specific location on my harddrive: 'C:\Folder\Data.xlsm'!Table1
If I want to manually change this back to a local reference, I have to first go through and disconnect every single slicer, refresh the tables, then reconnect every slicer. Not a viable solution for my clients.
I would use VBA to change the references every time Charts.xlsm is open, but when I tried it one of two things would happen: either the workbook produced errors that would prevent saving, or Excel would crash completely.
This is the code that works perfectly for disconnecting the slicers, but produces the 'save' error:
Sub Disconnect_Slicers()
Dim oSliceCache As SlicerCache
Dim PT As PivotTable
Dim i As Long
For Each oSliceCache In ThisWorkbook.SlicerCaches
With ActiveWorkbook.SlicerCaches(oSliceCache.Name).PivotTables
For i = .Count To 1 Step -1
.RemovePivotTable (.Item(i))
Next i
End With
Next oSliceCache
End Sub
So... I am asking the Excel/VBA geniuses out there if there is any way I can maintain a relative location for my charts when they are looking for Data.xlsm so that no matter what computer I open those workbooks on, they will always be actively linked.
Thank you SO much in advance!
If always both files are in the same folder you could possibly go this way.
A. Switch off auto 'UpdateLinks' of Chart.xlsm file. You could do this once manually or, for safety reason, always when BeforeClose event fires to avoid some possible problems:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.UpdateLinks = xlUpdateLinksNever
End Sub
B. When you open Chart.xlsm change the link to Data.Xlsm using Workbook Open event + additionally refresh links. In this situation we check path to Chart.Xlsm file and search Data.Xlsm in the same folder. I assume that there is only one link to any other file otherwise some changes could be required:
Private Sub Workbook_Open()
'changing first and only one link to new one
Dim a
a = ActiveWorkbook.LinkSources
ThisWorkbook.ChangeLink Name:=a(1), _
NewName:=ThisWorkbook.Path & "\Data.xlsm", Type:=xlExcelLinks
'update the link
ThisWorkbook.UpdateLink Name:=a(1), Type:=xlExcelLinks
End Sub
I admit I do not consider all the risks therefore some test are required.