How to take backup of current sheet or workbook - excel

Hy, I have an excel workbook which consists of six worksheets. Everything is working fine in the workbook. I have written a macro which helps me to take the backup of current workbook instead of the current worksheet. The code is as under.
Sub FileSaveAs()
Dim strFolder As String
Dim i As Long
'Find the position of the period in the file name
i = InStr(ActiveWorkbook.Name, ".")
'Create a default file name by concatenating the file name without the extention _
plus the current date and time, and plus the xlsm extention
Filename = Left(ActiveWorkbook.Name, i - 1) & "_" & Format(Now, "yyyy-mm-dd_hh mm") & ".xlsm"
'Open Save As dialog to a default folder with default file name
With Application.FileDialog(msoFileDialogSaveAs)
.AllowMultiSelect = False
.FilterIndex = 2 '2 = xlsm
.InitialFileName = "Report" & Filename
.InitialView = msoFileDialogViewDetails
If .Show = -1 Then strFolder = .SelectedItems(1) Else Exit Sub
.Execute
End With
End Sub
It is working fine for taking backup of workbook instead of the current working sheet without losing any data or formate or setting in the worksheet.
I have two problems.
1- When I click on the backup button, the active workbook is closed and backup workbook is opened.
2- I tried my best to take the backup of the current working sheet without losing any data or formating but I cloud not do so because everything when I click on the backup button for the current worksheet (I have written another macro to take backup for current worksheet but it is not working so I did not write it here) is lost.
What I want to do. I want to do two things.
1- When I click the backup button, the original worksheet remain open while the backup worksheet should remain close, so that I can take different name backups from same master worksheet.
2- If possible, I want a macro which helps me to take the backup of the active sheet without losing any data or information on the sheet.
Please guide where i am doing wrong. Thanks for every member.

Try,
Sub FileSaveAs()
Dim strFolder As String
Dim i As Long
Dim Fn As String
Dim Wb As Workbook
Set Wb = ThisWorkbook
Fn = Wb.FullName
Wb.Save
'Find the position of the period in the file name
i = InStr(ActiveWorkbook.Name, ".")
'Create a default file name by concatenating the file name without the extention _
plus the current date and time, and plus the xlsm extention
Filename = Left(ActiveWorkbook.Name, i - 1) & "_" & Format(Now, "yyyy-mm-dd_hh mm") & ".xlsm"
'Open Save As dialog to a default folder with default file name
With Application.FileDialog(msoFileDialogSaveAs)
.AllowMultiSelect = False
.FilterIndex = 2 '2 = xlsm
.InitialFileName = "Report" & Filename
.InitialView = msoFileDialogViewDetails
If .Show = -1 Then strFolder = .SelectedItems(1) Else Exit Sub
.Execute
End With
Set Wb = ActiveWorkbook
Workbooks.Open (Fn)
Wb.Close (0)
End Sub

Related

Do something while in VBA

I have a lot of files in one folder. What I want to do is add a column with the name of the file. I found a solution to this, but I want to optimize. Currently I am just adding the values from J2 to J1000 to make sure I cover all rows. This is not ideal as the amount of rows in each file differ. What I want to do is find a way to add the value matching the amount of rows that exists in the sheet.
I want to find a way to check if there is data in column A for each row and then add the value as long as there is some data in column A for each row.
My thoughts would be to do a while statement to check if each row in column A is different from an empty string and add the value as long as it is different from an empty string. However I am not sure how to implement this.
Here is my code:
Sub AllWorkbooks()
Dim MyFolder As String 'Path collected from the folder picker dialog
Dim MyFile As String 'Filename obtained by DIR function
Dim wbk As Workbook 'Used to loop through each workbook
On Error Resume Next
Application.ScreenUpdating = False
'Opens the folder picker dialog to allow user selection
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select a folder"
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder
End With
MyFile = Dir(MyFolder) 'DIR gets the first file of the folder
'Loop through all files in a folder until DIR cannot find anymore
Do While MyFile <> ""
'Opens the file and assigns to the wbk variable for future use
Set wbk = Workbooks.Open(FileName:=MyFolder & MyFile)
'Replace the line below with the statements you would want your macro to perform
Sheets(1).Range("j1").Value = "Date"
Sheets(1).Range("j2:j1000").Value = Mid(ActiveWorkbook.Name, 10, 10)
wbk.Close savechanges:=True
MyFile = Dir 'DIR gets the next file in the folder
Loop
Application.ScreenUpdating = 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.

Bulk rename worksheets to workbook (file) names in specfic folder

I have 90 Excel sheets in a folder: each Excel file has a unique name (company number) and contains only one worksheet. However the sheet name is generically named to 'Sheet1' in all files. Is there a VBA code that can rename all these sheets in this folder to their respective file name, minus the '.xlsx'?
Basically I want to combine all sheets to one file (I already have that VBA script). However before I can proceed with that, I have to rename all excel sheet names to their unique identifier (which is the file name).
I already looked online, but didn't see this script yet or saw this script for similar other purposes. Thanks in advance!
I found a solution online, credits to user VoG on https://www.mrexcel.com/forum/excel-questions/660913-vba-code-bulk-rename-first-worksheet-dependent-workbook-name.html
This is the solution. Change MyFolder = "C:\example" to respective folder
Sub RenSheets()
Dim MyFolder As String
Dim MyFile As String
Dim wbname As String
MyFolder = "C:\example"
MyFile = Dir(MyFolder & "\*.xls")
Application.ScreenUpdating = False
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile
With ActiveWorkbook
wbname = Left(.Name, InStr(.Name, ".") - 1)
.Sheets(1).Name = wbname
.Close savechanges:=True
End With
MyFile = Dir
Loop
Application.ScreenUpdating = True
End Sub

Create report from multiple excel files which are added automatically to the folder with different file names

I would like to know if this is possible so please don't see this as a "create my project for me" post
We are sending usage reports to our customers once a quarter (every 90 days from the date they bought the license). This report contains major tables with 30+ columns of raw number data.
I want to create a simple >drag new report into folder >paste results of main workbook into report
Creating a this is obviously simple but I want to:
Download the usage report (the filename represents the client
name)
Store all these reports in a single folder
Have the core workbook detect new file
Core workbook reads the new excel file, adds the data to a new sheet on the core workbook
Delete the workbook (the new usage report dragged into the folder) after the data has been added
Core workbook creates appropriate content (graphs etc) from the
new data
Are 3, 4, and 5 possible with VBA? I am not familiar with it at all and only recently discovered the possibility of macros in excel.
Below I have a macro which opens all workbooks in a folder one by one, you'll notice where I have commented out a section, here you can enter your code and perform an action on the given workbook. This will loop through each workbook in your folder until there isn't any left.
Sub ImportMacro()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them'
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Values in sheets'
Dim VolatilityPortfolio As String
Dim ColValue As String
VolatilityPortfolio = "VolatilityPortfolio"
'Optimize Macro Speed'
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User'
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel'
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")'
myExtension = "*.xl??"
'Target Path with Ending Extention'
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder'
Do While myFile <> ""
'Set variable equal to opened workbook'
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'-------------------- Below is the worksheet macro --------------------------'
'To open the currentworkbook
Workbooks(myFile).activate
'---------------------------- Above is the worksheet macro ----------------------- '
'Save and Close Workbook as CSV'
wb.Close SaveChanges:=True
'Get next file name'
myFile = Dir
Loop
'Message Box when tasks are completed'
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings'
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub

How can I open multiple Excel files and execute a contained macro on each?

I'm looking to open multiple Excel files and run the same macro (contained in each) on each file.
For example, I'd like to automatically open every file in h:\dbs and execute the CmdUpdate_Click macro within each file.
How might I go about this?
Try something like this. I expect you can research how to open the Visual Basic Editor and figure out where to paste this.
'Declare variables
Dim FolderObj, FSO, FileObj As Object
Dim FolderDialog As FileDialog
'Create and run dialog box object
Set FolderDialog = Application.FileDialog(msoFileDialogFolderPicker)
With FolderDialog
.ButtonName = "Select"
.AllowMultiSelect = False
.InitialFileName = "B:\BIM Projects\"
.InitialView = msoFileDialogViewDetails
'Check if user canceled dialog box
'Exit if yes
If .Show = -1 Then
MsgBox "No Folder Selected"
Exit Sub
End If
End With
'Check if user canceled dialog box
'Exit if yes
'Create a File System Object to be the folder that was selected
Set FSO = CreateObject("scripting.filesystemobject")
Set FolderObj = FSO.getfolder(FolderLocation)
'For each obj in the selected folder
For Each FileObj In FolderObj.Files
'Test if the file extension contains "xl" and make sure it's an Excel file before opening
If InStr(1, Right(FileObj.Name, Len(FileObj.Name) - InStr(1, FileObj.Name, ".")), "xl") = 1 Then
'Prevent the workbook from displaying
ActiveWindow.Visible = False
'Open the Workbook
Workbooks.Open (FolderObj & "\" & FileObj.Name)
'Run the Macro
Application.Run "'" & FolderObj & "\" & FileObj.Name & "'!CmdUpdate_Click"
'Save the Workbook
Workbooks(FileObj.Name).Save
'Close the Workbook
Workbooks(FileObj.Name.Close
End If
'Turn this back on
ActiveWindow.Visible = True
Next
I will caution you that this is based on some code I wrote for Word, so there are no guarantees it will work and I don't have time to test it. It will, however, give you a very good start if it doesn't.
Edit to Add: You may

Resources