I have the following macro that "Save As" a copy of the excel doc.
Sub STEP3SaveAs()
Application.GetSaveAsFilename
End Sub
BUT, every time I "Save As", I land on the doc I just saved...
I need assistance with a Macro that will "Save As", and leave me on the doc that I was working on.
Any assistance will be highly appreciated.
The issue here is that GetSaveAsFilename does not save at all. This just shows a dialog to choose a filename, but does not save it.
You can use the Workbook.SaveCopyAs Method to save a copy of your actual workbook.
Public Sub SaveCopy()
Dim Filename As String
Filename = Application.GetSaveAsFilename 'choose filename
ThisWorkbook.SaveCopyAs(Filename)
End Sub
You can do .SaveAs twice, thus it would return you the original workbook. The ThisWorkbook.FullName is a way to obtain the path:
Sub TestMe()
Dim saveName As String
Dim oldName As String
With ThisWorkbook
oldName = .FullName
saveName = Application.GetSaveAsFilename
.SaveAs saveName
.SaveAs oldName
End With
End Sub
Related
I am trying to create a macro to save a word document to a specific file. Here is the vba macro I have so far...
Sub Test1()
Dim path As String
path = "C:\Users\aroldan\OneDrive\Documents\02 - PENDING\"
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=path
Application.DisplayAlerts = True
ActiveWorkbook.Close
End Sub
I am running this on a Word, while many tutorials show this on Excel.
Thank you!
You just need to make the changes already suggested. Adding the file name to the path is enough:
Sub SaveAFile()
Dim path As String
path = "C:\Users\User\Test.docx"
With ActiveDocument
.SaveAs FileName:=path
.Close
End With
End Sub
When searching for VBA specific to Word, search on "Word" VBA -Excel, plus the subject keywords.
From a Personal.xlsb file, I want VBA to save the current active workbook as a user-definable name in the same directory and delete the original workbook.
Below is my code. It has two problems. One, it saves the workbook in My Documents folder for some reason. The active workbook is not in My Documents. It's in a folder in a completely different drive. Two, it throws a "File not found" error.
Sub RenameFile()
Dim thisWb As Workbook
Set thisWb = ActiveWorkbook
MyOldName = ActiveWorkbook.Name
MyNewName = InputBox("What do you want to rename the file as?", "Rename", ActiveWorkbook.Name)
ActiveWorkbook.SaveAs Filename:=thisWb.Path & MyNewName
Kill MyOldName
End Sub
You need to include a \ after path and before filename.
Sub RenameFile()
Dim thisWb As Workbook
Set thisWb = ActiveWorkbook
MyOldName = ActiveWorkbook.FullName
MyNewName = InputBox("What do you want to rename the file as?", "Rename", ActiveWorkbook.Name)
ActiveWorkbook.SaveAs Filename:=thisWb.Path & "\" & MyNewName
Kill MyOldName
End Sub
Edit: Updated answer to include fix from comment.
So I have some code that I use to auto save files (to a directory specified in the code) and then deletes a particular file type out of said folder. (I use it to save a .xlsx and delete .csv)
'Saves file to specified location
ActiveWorkbook.SaveAs filename:="C:\Desktop\Testing\Testing File " _
& Format(Now() - 1, "DD.MM.YY") & ".xlsx" _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
On Error Resume Next
Kill "C:\Desktop\Testing*.csv*"
On Error GoTo 0
This is the code that I used that is within a longer VBA module, but you could incorporate this into existing VBA code
Take note that that currently saves the file as Testing with the day before the current system date in the name, such as "Testing 30.10.16"
I have added a button in excel sheet and added following codes in vba window of that button. Now when I click this button i.e. when I run the codes it saves the excel sheet in pdf form whose name it takes from cell no H8 and saves it at M:\formats. Moreover it also saves the same excel sheet in .xlsx format at M:\formats\excels. But here the problem is when I run the codes it closes the excel sheet in which I have added the codes and opens the file which is saved by the codes. For example I made abc.xlsm excel sheet and added the codes in vb window, now xyz is written in cell no h8 in abc.xlsm excel sheet, now when I will run the codes it closes abc.xlsm and all codes are shown in xyz.xlsx excel sheet. I want it should only save the file in xlsx format it requisite location. It should not close the base file (which is abc.xlsx in the above example) and should not open the saved file (which is xyz.xlsx in the above example). Moreover I want that the saved file (xyz.xlsx in the above example) should not contain any vba coding. In another words it should be just like the backup copy for the base file (which is abc.xlsx in the above example). Kindly help me in to modify these codes to them as I want. I will be highly obliged to you. Thanks
Sub ExportAPDF_and_SaveAsXLSX()
Dim wsThisWorkSheet As Worksheet
Dim objFileSystemObject As New Scripting.FileSystemObject
Dim strFileName As String
Dim strBasePath As String
strBasePath = "M:\formats\"
strFileName = Range("H8")
On Error GoTo errHandler
Set wsThisWorkSheet = ActiveSheet
wsThisWorkSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strBasePath & strFileName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created."
strBasePath = "M:\formats\excels\"
strFileName = Range("H8")
Application.DisplayAlerts = False
strFileName = objFileSystemObject.GetBaseName(strFileName) & ".xlsx"
wsThisWorkSheet.SaveAs Filename:=strBasePath & strFileName,
FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = False
MsgBox "Workbook now saved in XLSX format."
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
Here is the code, with just two small changes. Both new sets of lines have the comment "New" in front of them.
Also just tidied up the error handling routine a little bit.
The way it works is this:
Store the filename of the current workbook in the variable 'strMasterWorkbookFilename'
The PDF file is created by 'exporting' the worksheet.
The Excel worksheet is then saved as an XLSX. This effectively 'closes' the original workbook.
3.1 The Button ("Button 8") is removed from the new XLSX worksheet and the workbook is saved again.
The code then re-opens the original workbook ('strMasterWorkbookFilename') and closes the current workbook.
Notes - Saving as the XLSX will remove the Macro code from the saved file. The Macro will remain in the main 'master' file.
Sub ExportAPDF_and_SaveAsXLSX()
Dim wsThisWorkSheet As Worksheet
Dim objFileSystemObject As New Scripting.FileSystemObject
Dim strFileName As String
Dim strBasePath As String
' NEW
Dim strMasterWorkbookFilename As String
strMasterWorkbookFilename = ThisWorkbook.FullName
strBasePath = "M:\formats\"
strFileName = Range("H8")
On Error GoTo errHandler
Set wsThisWorkSheet = ActiveSheet
wsThisWorkSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strBasePath & strFileName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created."
Application.DisplayAlerts = False
strFileName = objFileSystemObject.GetBaseName(strFileName) & ".xlsx"
wsThisWorkSheet.SaveAs Filename:=strBasePath & strFileName, FileFormat:=xlOpenXMLWorkbook
wsThisWorkSheet.Shapes("Button 8").Delete
ActiveWorkbook.Save
Application.DisplayAlerts = False
MsgBox "Workbook now saved in XLSX format."
' NEW
Workbooks.Open strMasterWorkbookFilename
Workbooks(strFileName).Close SaveChanges:=False
exitHandler:
Exit Sub
errHandler:
MsgBox "Error Saving file. The error is " & vbCrLf & Chr(34) & Err.Description & Chr(34)
Resume exitHandler
End Sub
Thanks for posting this as a new question. If I'd carried on modifying the original code in the first question, it would not have been useful for anyone else reading your original post.
I recorded vba code to do some conditional formatting. The result is stored in the workbook itself. Now I want to force the user not to save the workbook, instead after the code is run, it should automatically save the workbook using "Save As" into a non macro file using some unique identifier such as "yyyymmmdd, hhmm.xlsx" and it should also ask the user where to save.
Additionally, it should close the workbook without saving it and open the last saved as .xlsx file. I found some codes, but they are not exactly what I am looking for. Please help.
How about this
Option Explicit
Sub SaveAs()
Dim sDate As String
Dim FileName As String
'// format Date
sDate = Format(Now, "YYYYMMDD HHMM")
'// Save As Name
FileName = sDate
'// Save path
Application.Dialogs(xlDialogSaveAs).Show FileName
End Sub
add this code below your code
Per OP Comment
This should do it - Tested on Excel 2010
Option Explicit
Sub SaveAs()
Dim xlSaveAs As String
Dim xlPath As Variant
Application.ScreenUpdating = False
'// Save As Name
xlSaveAs = "Weekly Report - " & Format(Now, "YYYYMMDD HHMM") & ".xlsx"
'// Save path
Application.DisplayAlerts = False
xlPath = Application.GetSaveAsFilename( _
InitialFileName:=xlSaveAs, _
FileFilter:="Excel Files (*.xlsx), *.xlsx", _
Title:="My Save Dialog")
If xlPath <> False Then
ThisWorkbook.SaveAs xlPath, xlOpenXMLWorkbook
Else
MsgBox "Not Valid Path" '// Cancel
End If
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Finally, You may find the Getting Started with VBA in Office 2010 article in MSDN helpful.
edit : I rewrite the code to do what you want
Public Sub SaveNewFile()
' Create a new file basing the name of the current file (without extension if it's an xlsm) and the creation time
Dim filename As String
filename = ThisWorkbook.Path & "\" & CreateObject("scripting.filesystemobject").getbasename(ThisWorkbook.Name) & Format(Now, "yyyyMMdd hhmm") & ".xlsx"
' Save the file under the new name in xlsx format
' This action close the file and reopen it with the new name
Application.DisplayAlerts = False
ThisWorkbook.SaveAs filename:=filename, FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = True
End Sub
I cannot seem to get a definite feedback on whether or not a read-only workbook is opened or not. In my code I have it copy after closing/saving the workbook. I would like to be able to overwrite the read-only workbook if it's opened as read-only by another user. I tried this something like this bit of code, but had no luck, it just kept saying "File not open!" even when I had it opened.
How can I check whether or not a "read-only .xlsx" file is opened or not in vba?
Sub Test_If_File_Is_Open_2()
Dim wBook As Workbook
On Error Resume Next
Set wBook = Workbooks("C:\Users\" & Environ("username") & "\Documents\Dropbox\Systems\Open Machine Schedule\Open Machine Schedule.xlsx")
If wBook Is Nothing Then 'Not open
MsgBox "File is Not open!"
Else 'It is open
MsgBox "File is Open!" 'Never get this to display when I have the excel file open
End If
End Sub
What started the prompt for using this bit of code(above) was because I wanted the macro to not cause an error if the read-only workbook was opened by another user. When I run the macro below and have the copied read-only workbook opened prior, I get an error:"vba run time error 1004 cannot access read-only document"
I don't get this error when the copied workbook is closed, it overwrites it like it's supposed to.
Here is the code that prompted this question:
Option Explicit
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim backupfolder As String
backupfolder = "C:\Users\" & Environ("username") & "\Documents\Dropbox\Systems\Open Machine Schedule\"
ThisWorkbook.SaveAs Filename:=backupfolder & "Open Machine Schedule - Current.xlsx", FileFormat:=xlOpenXMLWorkbook
End Sub
Sub Auto_Save()
Dim savedate
savedate = Date
Dim savetime
savetime = Time
Dim formattime As String
formattime = Format(savetime, "hh.MM.ss")
Dim formatdate As String
formatdate = Format(savedate, "DD - MM - YYYY")
Application.DisplayAlerts = False
Dim backupfolder As String
backupfolder = "C:\Users\" & Environ("username") & "\Documents\Dropbox\Systems\Open Machine Schedule\"
ActiveWorkbook.Save
ActiveWorkbook.SaveAs backupfolder & "Open Machine Schedule - Current.xlsx", FileFormat:=xlOpenXMLWorkbook
SetAttr backupfolder & "Open Machine Schedule - Current.xlsx", vbReadOnly
Application.DisplayAlerts = True
MsgBox "Backup Run. Please Check at: " & backupfolder & " !"
End Sub
Any help/suggestions would be much appreciated
your first code is only testing to see if a workbook exist not its state.
You could use this instead:
If wBook.ReadOnly Then
MsgBox "File is Read-only"
Else
MsgBox "File is not read-only"
End If