Delete Cell content after Saveas - excel

I am trying to delete the contents of few cell in the saved copies of my workbook that is under different file names. As code below, this is deleting the content from original workbook and retaining the content in the saved wb. It is doing the right opposite task that I wanted for!
Also, any suggestion on how to disable few modules and delete few pictures in the saved wb ?
Thanks in Advance for help !
Sub SaveAsNewCopy()
Dim Path As String
Dim FileName1 As String
Application.DisplayAlerts = False
FileName1 = Range("D3")
ThisWorkbook.SaveCopyAs FileName:="C:\Users\..\..\..\" & FileName1 & "-" & "List" & ".xlsm"
MsgBox "File Saved successfully!", , "Save"
ThisWorkbook.Sheets("Sheet1").Range("E5:F5").ClearContents
ThisWorkbook.Sheets("Sheet1").Range("E9:F9").ClearContents
Application.DisplayAlerts = True
End Sub

You need to get a handle on the workbook you just saved, make the changes you want and then save it again. The easiest way to do this is to assign a variable to it. In your declarations do something like this:
Dim wb as Workbook
then before your save-as line assign the saved workbook to that variable like this:
Set wb = ThisWorkbook.SaveCopyAs FileName:="C:\Users......\" & FileName1 & "-" & "List" & ".xlsm"
Then you can work with wb as required as save it with wb.Save True etc etc

Related

How to save copy of Excel workbook?

I've been trying to make a macro that automatically saves a backup copy of my Excel workbook before I edit any of its data.
Every time I call it, even though it successfully saves a new copy, when it reaches the end the code stops execution, and macros I try to call below it don't execute.
I think when I run the code and the new backup version is created, the code continues to run on the backup workbook instead of the main workbook, so when I close the backup workbook I abruptly end the code.
I'd like to save a backup version of my main workbook, close the backup version and continue the code on the main workbook.
Public Sub BackupWorkbook()
Dim CurrentFile As String, BackupFile As String, DesiredWorkbookName As String
Dim NowDate As String
'Save current code and Excel spreadsheet data
ActiveWorkbook.Save
'Get necessary strings for filenames
CurrentFile = ThisWorkbook.FullName
NowDate = Replace(Format(Now, "dd-mm-yyyy, hh:mm:ss"), ":", ".")
BackupFile = ThisWorkbook.Path & "\" & "Chem Chart Backups" & "\" & "Chemical Chart" _
& " (" & NowDate & ")" & ".xlsm"
'Save as active workbook to backup file location, then reopen main workbook
ActiveWorkbook.SaveAs BackupFile, FileFormat:=52
Workbooks.Open CurrentFile
'This should close the backup version of workbook that opened because of SaveAs method
Workbooks(DesiredWorkbookName & " (" & NowDate & ")" & ".xlsm").Close SaveChanges:=True
End Sub
Public Sub TestMacros()
Call BackupWorkbook
'If this message box pops up after macro is called, it is successful
MsgBox "Success!"
End Sub
I use
Sub BackUp()
Dim BackUpPath As String
BackUpPath = "Your path"
Dim BackUpFile As String
BackUpFile = BackUpPath & "BackUp.xlsm"
ThisWorkbook.SaveCopyAs Filename:=BackUpFile
End Sub
I call this at various times in my project to backup the document as required, this seems to work okay for me and my code will continue to run in the original workbook.
I also generate a unique filename each time and do not actually use "BackUp" as the name of the new workbook as this overwrites my previous backup so I would recommend doing something similar.

Protecting a new excel sheet that has been exported

I have the following macro that exports a current excel sheet with some data to a new workbook into a specific path. The trouble i have, is that i want to protect that workbook new sheet after is created. How it can be done? I tried using ActiveWorkbook.Protect "Password" but did not worked.
Sub NuevoDia()
Dim FilePath As String
Dim NewName As String
FilePath = "C:\Users\Pol\Desktop\": NewName = FilePath & "Registros " & Format(Date, "DD-MM-YYYY") & ".xls"
Sheets("Registros").Select
Hoja3.Unprotect "LOG2020"
Sheets("Registros").Copy
ActiveWorkbook.SaveAs Filename:=NewName, FileFormat _
:=xlWorkbookNormal, CreateBackup:=False
End Sub
Thanks for the help!
To protect a sheet I would suggest to do :
Sheets("Registros").Protect "password"
And if you wanted to protect workbook since you tried :
ActiveWorkbook.Protect Password:="password", Structure:=True, Windows:=True
Also note that it is better to not use select so
Sheets("Registros").Select
Hoja3.Unprotect "LOG2020"
Sheets("Registros").Copy
do the same as
Hoja3.Unprotect "LOG2020"
Sheets("Registros").Copy

Subscript out of range when copying range to another workbook

I am writing a reporting system where the user fills out a form and a form button runs a macro to save the file with a name based on several fields including a timestamp.
All the data is is also on a second sheet but in one row for ease of copying to a master sheet.
I am trying to to extend the save macro to copy this row to the last line of a second workbook.
This was successful when the macro was run from a separate workbook but I can't for the life of me work out how to do it from within the file itself.
I've triple checked the paths themselves, I know they're right as the new files are being created, I've run msgbox in the code to check the filename and the variable are the same too.
timestampedfile = Worksheets("single_line").Range("b3")
totalpath = Path & timestampedfile & ".xlsm"
ActiveWorkbook.SaveCopyAs filename:=totalpath
master_wb = "s:\blah\blah\blah.xlsx"
master_sht = "Master_Database"
contact_wb = totalpath
contact_sht = "single_line"
Workbooks.Open (master_wb)
Workbooks.Open (contact_wb)
MsgBox (totalpath)
Workbooks(contact_wb).Worksheets(contact_sht).Range("A3:AQ3").Copy Worksheets(master_wb).Sheets(master_sht).Range("A" & Rows.Count).End(xlUp)(2)
'
Both the Workbooks open so I know the paths are right, can anyone help?
Solution by OP
Solved thanks to comment about workbook variables by BigBen:
Use workbook variables, instead of referencing the workbook by name: Dim masterWb as Workbook, then Set masterWb = Workbooks.Open("s:\blah\blah\blah.xlsx" ). Similarly for the contact workbook. You might consider using worksheet variables too, instead of using sheet names.
Code changed to:
Dim master_wb As Workbook
Dim contact_wb As Workbook
Dim master_sht As Worksheet
Dim contact_sht As Worksheet
Path = "S:\blah\" & Worksheets("report").Range("c8") & "\"
filename = Worksheets("back_end_formulas").Range("e10")
timestampedfile = Worksheets("single_line").Range("b3")
totalpath = Path & timestampedfile & ".xlsm"
ActiveWorkbook.SaveCopyAs filename:=totalpath
SetAttr totalpath, vbReadOnly
Set master_wb = Workbooks.Open("S:\blah\Master_Database2.xlsx")
Set master_sht = master_wb.Sheets("Master_Database")
Set contact_wb = Workbooks.Open(totalpath)
Set contact_sht = contact_wb.Sheets("single_line")
ThisWorkbook.Activate
contact_sht.Range("A3:AQ3").Copy master_sht.Range("A" & Rows.Count).End(xlUp)(2)
master_wb.Close SaveChanges:=True
contact_wb.Close SaveChanges:=False
ActiveWorkbook.Close SaveChanges:=False

Save a copy of a file in a specific folder on opening the file

I have an Excel workbook that is used by a lot of people and can easily be ruined.
How can I by opening the Excel workbook (file) automatically save a copy to a specific folder?
The Excel workbook is in SharePoint so I can create a new folder in the same location with the name 'Archive' and by opening the file a new copy of that file with the same name + "DD.MM.YYY HH:MM:SS" will be saved here.
I'm not sure about sharepoint, but this work if the file is saved in a regular folder. Solution could be made in different ways.
Save the code in the following place in the VBA Editor. Name the sub to "Private Sub Workbook_Open()" - to indicate that excel should execute the code when it opens up.
You can see that you have succeed when the "procedure" field changes to "Open", marked yellow in the picture.
Alternative 1:
Here I hardcode my path by writing "G:\Till\". Then I proceed with adding the timestamp and choose which format. Notice for time you can't use the semicolon ":" in the path. One way is to add "T" for Time and then the hour+minute+second.
In my example code the result will be: "Data Example - 2019-11-03 T203533.xlsm"
Notice that this code will get a Error 1004, if the path doesn't exist.
Private Sub Workbook_Open()
Dim Fldr As String
Application.DisplayAlerts = False 'Hide any save window pop-up
ActiveWorkbook.SaveCopyAs Filename:="G:\Till\" & "Data Example - " & Format(Now(), "yyyy-MM-dd Thhmmss") & ".xlsm" 'Save the workbook as a copy of the original. Add Hour and timestamp
Application.DisplayAlerts = True
End Sub
Alternative 2:
To make the code more robust I check the pathway of the workbook I use and then check if the folder "Archive" exists. If it doesn't exist it will create the folder and save a copy of the file.
Private Sub Workbook_Open()
Dim Fldr As String
Application.DisplayAlerts = False 'Hide any save window pop-up
Fldr = Dir(Application.ActiveWorkbook.Path & "\Archive\", vbDirectory) 'Check if folder exists. The variable will be empty if no folder exists.
If Fldr = Empty Then 'If no folder exist, the variable "Folder"
MkDir Application.ActiveWorkbook.Path & "\Archive\" 'Create the folder
End If
ActiveWorkbook.SaveCopyAs Filename:=Application.ActiveWorkbook.Path & "\Archive\" & "Data Example - " & Format(Now(), "yyyy-MM-dd Thhmmss") & ".xlsm"
Application.DisplayAlerts = True
End Sub

Saving a macro so that the file can be updated

Background Information - I have two buttons, that both run a set of code. The excel file has over 30 columns and 65,000 rows. This file is exported (.csv) from somewhere and is updated biweekly.
Goal - have the new file saved with the same name as the old. So that the values can be updated, buttons are still available and the code can run again with the new file.
Or That when a new file is exported, it is saved in a folder that runs the code INDEPENDENT of the user path. i.e Pathname = ActiveWorkbook.Path & "C:\Users\"this can be any name"\Desktop\Downloads\"
Attempt
Used a similar code to the one in a previous question "Run same excel macro on multiple excel files" with edits to tailor for my code. With no success
Sub ProcessFiles()
Dim Filename, Pathname As String
Dim wb As Workbook
Pathname = ActiveWorkbook.Path & "\Files\"
Filename = Dir(Pathname & "*.xls")
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
DoWork wb
wb.Close SaveChanges:=True
Filename = Dir()
Loop
End Sub
Currently, when I attempt the first method I only replace (Old file + VBA) with (New file).
Please note that the solution does not need to be a VBA code. If it's just saving the file in a new method that stores the macro and updates the values I would be happy.
An example of my previous answer:
Sub SaveThisAs()
Dim wb As Workbook: Set wb = ThisWorkbook 'ThisWorkbook referrs to the workbook the macro is ran from
Dim PathToSaveTo As String
PathToSaveTo = wb.Path & "\"
PathToSaveTo = PathToSaveTo & Format(Now, "ddMMyyyy_hhmmss") & wb.Name 'Lets add a timestamp
'Do your macro stuff here
'....
'Save the workbook
wb.SaveAs PathToSaveTo
End Sub
Please note that I'm using wb.Name at the end of the file to save to... this will be fine first time you run this, but a second time the name will get longer... and longer ... and longer. Adjust as per your needs with an appropriate file name.

Resources