Everytime I save my workbook I need to save the same workbook, but Hidden.
Now I have this code
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
ThisWorkbook.Saved = True
On Error Resume Next
If Not (Left(ThisWorkbook.Name, 2) = "Z_") Then
Application.DisplayAlerts = False
ThisWorkbook.SaveCopyAs ThisWorkbook.Path & "\Z_" & ThisWorkbook.Name
SetAttr ThisWorkbook.Path & "\Z_" & ThisWorkbook.Name, vbHidden
Application.DisplayAlerts = True
End If
SetAttr ThisWorkbook.Path & "\Z_" & ThisWorkbook.Name, vbHidden
End Sub
However it works only every second time. First time I save WB, it creates the file and make it hidden, but when I save it second time it deletes the hidden file.
When I use SaveAs with overwrite property it saves file and activate it, but I dont want that.
Why is that? How to solve this please?
When you have a problem like this, the first this to do is to comment out On Error Resume Next and Application.DisplayAlerts = False. That will give you far more information on what's going on.
In your case, you had a problem with preexisting files. Try this instead:
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Dim HiddenFileName As String
HiddenFileName = ThisWorkbook.Path & "\Z_" & ThisWorkbook.Name
ThisWorkbook.Saved = True
On Error Resume Next
If Not (Left(ThisWorkbook.Name, 2) = "Z_") Then
Application.DisplayAlerts = False
' Unhide and delete existing file
SetAttr HiddenFileName, vbNormal
Kill HiddenFileName
' Save new copy and hide it
ThisWorkbook.SaveCopyAs HiddenFileName
SetAttr HiddenFileName, vbHidden
Application.DisplayAlerts = True
End If
SetAttr HiddenFileName, vbHidden
End Sub
It unhides and deletes the file, before creating it again. This is a bit dirty, since it doesn't test if it exists before, but relies on On Error Resume Next.
Related
Below is my code for saving the file without the VBA codes.
It saves together with the VBA codes.
Sheets.Select
Cells.Copy
Cells.PasteSpecial xlPasteValues
Application.DisplayAlerts = False
ThisWorkbook.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C",
FileFormat:=xlExcel8
Application.DisplayAlerts = True
Next x
End Sub
Save your project as xlsx instead of xlsm then the Code shouln'd be saved
you could first copy sheets in a new workbook and then save it
Sheets.Copy
Sheets.Select
Cells.Copy
Cells.PasteSpecial xlPasteValues
Application.CutCopyMode = False
With ActiveWorkbook
Application.DisplayAlerts = False
.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C.xlsx"
Application.DisplayAlerts = True
.Close True
End With
from
ThisWorkbook.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C", FileFormat:=xlExcel8
to this:
ThisWorkbook.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C" & ".xlsx", FileFormat:=xlOpenXMLWorkbook
SaveAs Confusion
I'm confused, too. As it happens, when you save your macro enabled workbook (.xlsm) as macro not-enabled workbook (.xlsx), the workbook stays open still having the code in it. But the good thing is that it is saved without code. You can now save it, 'manually' SaveAs it, it will still be without code (macros) the next time you open it.
The code should demonstrate the following:
It is good practice to start with Option Explicit which will help
you by alerting you when something is wrong.
It is good practice to use constants at the beginning of the code,
especially for such long file paths, so when you have to change them
you can easily find them.
When you disable an event, there is a possibility you won't be able
to enable it again if you're not careful. If an error occurs, you should redirect
the code to enable those events again.
If you want to close the workbook, then use the line ThisWorkbook.Close
Option Explicit
Sub SaveMacroDisabled()
Const strPath = "I:\Excel\MyDocuments\Test\Test4\"
Const strXLSX = "BookMacroDisabled"
On Error GoTo ProgramError
Application.DisplayAlerts = False
ThisWorkbook.SaveAs strXLSX, _
FileFormat:=xlWorkbookDefault
SafeExit:
Application.DisplayAlerts = True
' ThisWorkbook.Close
Exit Sub
ProgramError:
MsgBox "An unexpected error occurred"
On Error GoTo 0
GoTo SafeExit
End Sub
I am trying to save my workbook every 10 minutes but I keep getting the run time error 1004. The code shown is in one of the modules. My program will save my entire workbook as today's date into a folder.
Everything was working perfectly fine until I ran the code and then saved it and now I get that error.
Sub CommandButton1_Click()
Dim path As String
Dim filename1 As String
path = "C:\Users\100020427\Desktop\FPYFiles\"
filename1 = ThisWorkbook.Sheets("Totals").Range("M10").Text
Application.DisplayAlerts = False
If ThisWorkbook.Name = filename1 Then
ThisWorkbook.save
MsgBox "Today's Form has been saved! Click Ok Button"
Else
ThisWorkbook.SaveAs Filename:=path & filename1, FileFormat:=52, CreateBackup:=False
MsgBox "Today's Form has been saved! Click Ok Button"
Application.DisplayAlerts = True
End If
'Application.DisplayAlerts = False
'ActiveWorkbook.save Filename:=path & filename1, FileFormat:=52, CreateBackup:=False
'Application.DisplayAlerts = True
Application.OnTime Now + TimeValue("00:01:00"), "CommandButton1_Click"
End Sub
Sub Workbook_Open()
CommandButton1_Click
Application.OnTime Now + TimeValue("00:01:00"), "CommandButton1_Click"
End Sub
I expect is to save workbook as the date in the listed location
If I understand your setup correctly, you are issuing a SaveAs-command every 10 minutes, and the filename will contain the current date. So, the filename is the same during the whole day, and that will cause a failure when the SaveAs is issued a second time.
Why? You ask Excel to overwrite an existing file. As you suppress warnings, you will not see the message "The file already exists, do you want to replace it?". Excel then tries to overwrite the last version of the file with the current one, but as the file is (obviously) open, this will fail.
Change your piece of code so that the SaveAs is only executed if you really write a new file. In all other cases, use Save rather than SaveAs. Note that I added the extension to the filename so that the check is successfull. I also fully qualified the cell where the filename is expected so that the code will not fail when a different sheet or workbook is currently active.
fileName1 = ThisWorkbook.Sheets(1).Range("M10") & ".xlsm"
If ThisWorkbook.Name = fileName1 Then
ThisWorkbook.Save
Else
ThisWorkbook.SaveAs path & fileName1, 52
End If
I would like a macro to undo ALL changes since the workbook was last opened/saved.
I thought this would be as easy as re-opening the workbook, similar to this answer:
https://stackoverflow.com/a/44244262/1473412
However, when I use:
Workbooks.Open(ThisWorkbook.FullName)
Literally NOTHING happens. No alert, no error, no change. It is as though the command is just ignored. Has this behaviour changed in recent versions of Excel?
What is the easiest way to revert a workbook to its previously saved state in the latest version of excel (2016)?
Thanks,
Try this workaround:
Public Sub ReOpenWithoutSave()
Application.EnableEvents = False
ThisWorkbook.Saved = True
ThisWorkbook.ChangeFileAccess xlReadOnly, , False
Application.Wait Now + TimeValue("00:00:01")
ThisWorkbook.ChangeFileAccess xlReadWrite, , True
Application.EnableEvents = True
End Sub
It marks ThisWorkbook as already saved (but does not save it).
It makes ThisWorkbook read only and waits 1 second to let it proceed
It makes ThisWorkbook writeable again (which causes a re-open automatically)
Logic:
Close the Excel file without saving and simply re-open it. But then how do I reopen it from the same file?
Create a VBScript from your code
Put a Delay of say 3 secs in that and the code to open the Excel file
Call the vbscript and close the current file.
Is this what you are trying?
Sub Sample()
Dim file As String
file = ThisWorkbook.Path & "\DeletemeLater.vbs"
Sheet1.Range("A2").Value = "Blah Blah" '<~~ This change will not be saved
'~~> Create a vbscript file
Open file For Output As #1
Print #1, "WScript.Sleep 300"
Print #1, "Set oExcelApp = GetObject(,""Excel.Application"")"
Print #1, "oExcelApp.Visible=True"
Print #1, "Set oWB = oExcelApp.Workbooks.Open(" & Chr(34) & ThisWorkbook.FullName & Chr(34) & ")"
Close #1
Shell "wscript " & Chr(34) & file & Chr(34), vbNormalFocus
ThisWorkbook.Close (False)
End Sub
And one more thing. Add this in the workbook code area
Private Sub Workbook_Open()
On Error Resume Next
Kill ThisWorkbook.Path & "\DeletemeLater.vbs"
On Error GoTo 0
End Sub
I would like to have a vba code which automatically makes the backup to a Folder in the SharePoint. I have found a Code which makes a duplicate file within the hard disk but not in SharePoint.
SharePoint link(https://web-mp01/sites/5034/SitePages/Home.aspx), I Need to do backup in this link.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.DisplayAlerts = False
ActiveWorkbook.SaveCopyAs Filename:="C:\TEMP\" & _
TesStr & "-" & TesStr & "-" & ActiveWorkbook.Name
ActiveWorkbook.Save
Application.DisplayAlerts = True
End Sub
I can't get my macro running in AfterSave or BeforeClose event.
I export one sheet to a .csv file, that's already working well with the next code when I link this macro to a button:
Sub CopyToCSV()
Worksheets("LastLots").UsedRange.Rows("1:5").Calculate
ThisWorkbook.Save
Dim MyPath As String
Dim MyFileName As String
'The path and file names:
MyPath = "D:\Data\PW\2018\"
MyFileName = "LastLots-exported"
'Makes sure the path name ends with "\":
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
'Makes sure the filename ends with ".csv"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
'Copies the sheet to a new workbook:
Sheets("LastLots").Copy
'The new workbook becomes Activeworkbook:
With ActiveWorkbook
Application.DisplayAlerts = False
'Saves the new workbook to given folder / filename:
.SaveAs Filename:= _
MyPath & MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False
'Closes the file
.Close False
Application.DisplayAlerts = True
End With
End Sub
The code above is in a module. As I said, when linked to a button and press that button, it works very well.
But I want it running when the user saved the file.
Fot this, I put the next code in ThisWorkbook:
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
If Success = True Then
Call CopyToCSV
End If
End Sub
I tried various things, like putting the code of the macro inside the AfterSave-event, and disable/enable Application.EnableEvents before and after calling CopyToCSV but nothing works for me...
Does anyone have a suggestion? I'm out of mind, and every topic I find on Google say to put the code in ThisWorkbook, but already done that.
Just typing the code somewhere does not make it an event handler.
You must enter "ThisWorkbook", look at the top bar, select "ThisWorkbook" and the desired event.
Excel will then automatically create the empty Sub for you, associated with the event. You insert your code inside that Sub.
More details: https://www.excelcampus.com/vba/code-modules-event-procedures/
Hints: before any if, test if the script is being run, add a message such as MsgBox "After save!!!"
This will help you identify if the problem is the event not being called or your code not being run properly.