Save As failed Excel VBA - vba

-Summary:
I'm trying write code that will automatically save with the name of the current date
-Problem: Error saying "Method 'SaveAs' of object '_Workbook' failed" pops up when compiler reaches the line that saves. Everything else works. I've shown the whole function for references' sake.
Function createRecord()
Dim rowCount As Integer
Dim theDate As Date
theDate = Format(Now(), "MM-DD-YY")
Sheets("New Data").Select
Cells.Select
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
Application.ActiveSheet.Name = "ChaseHistory"
ActiveSheet.Paste
rowCount = ActiveSheet.UsedRange.Rows.Count
Sheets("Exceptions").Select
'rowCount = ActiveSheet.UsedRange.Rows.Count
Application.CutCopyMode = False
ActiveSheet.UsedRange.Rows.Select
Selection.Copy
Sheets("ChaseHistory").Select
ActiveSheet.Range("A" & rowCount + 2).Select
ActiveSheet.Paste
Range("A1").Select
Cells.Select
Selection.Copy
ChDir "Z:\Customer_Service_Accounting\REPORTING & CONTROLS TEAM\Book And Balance_Katie\Chase Booking History" 'loads the crystal report
Workbooks.Open Filename:= _
"Z:\Customer_Service_Accounting\REPORTING & CONTROLS TEAM\Book And Balance_Katie\Chase Booking History\Do_Not_Delete.xlsx"
Windows("Do_Not_Delete").Activate
ActiveSheet.Paste
Application.DisplayAlerts = False
'---------------This is the problem child-------------- 'SAVING WORKBOOK
ActiveWorkbook.SaveAs Filename:="Z:\Customer_Service_Accounting\REPORTING & CONTROLS TEAM\Book And Balance_Katie\Chase Booking History\" & CStr(theDate), FileFormat:= _
xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
, CreateBackup:=False
Application.DisplayAlerts = True
End Function
-I added in the convert to string method on date because I thought that might be causing the problem but had the same result. Let me know if you see anything wrong here. Thanks!

The Problem: because in my code I was disabling prompts from excel, when I was trying to save I wasn't seeing a prompt telling me that I was attempting to save with an improper format.
Basically to sum it up, Excel didn't like that I had backslashes ("/") in my filename (which I really should have known)
The Fix: I ended up using this statement:
ActiveWorkbook.SaveAs Filename:="Z:...\" & "Chase " & _
Month(theDate) & "_" & Day(theDate) & "_" & Year(theDate) & ".xlsx"
So all I really did here was post month, day, and year together into a string separated by underscores to avoid the evil backslash.
Thanks for your help Gaffi!

Have you tried something like this?
ActiveWorkbook.SaveAs Filename:="Z:\Customer_Service_Accounting\REPORTING & CONTROLS TEAM\Book And Balance_Katie\Chase Booking History\" & Format(theDate, "mm.dd.yy"), FileFormat:= _
xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
, CreateBackup:=False
To highlight: I changed CStr(theDate) to Format(theDate, "mm.dd.yy") & ".xlsx", but you can use other formats if needed.
Explanation:
theDate is of type Date (see: Dim theDate As Date), so what is returned is a complete date/time format string when you use CStr(). This will result in something like this:
Debug.Print CStr(Now())
7/6/2012 7:23:38 AM
Which will likely cause your system to reject for invalid characters in the filename.

Related

Automatically Save File as Text With Friday's Date

I recorded a macro that at the end saves the workbook as a text file and closes.
I would like to change the file name to Friday's date so that every week when I save it, the file name is different.
This is what the macro recorded
ActiveWorkbook.SaveAs Filename:= _
"C:\Users\username\Desktop\Temp\\File2218.txt" _
, FileFormat:=xlText, CreateBackup:=False
I tried to change it to
ActiveWorkbook.SaveAs Filename:= _
"C:\Users\username\Desktop\Temp\File" & Text(Today()+2, "mdyy")& txt" _
, FileFormat:=xlText, CreateBackup:=False
(The reason I did +2 is because it's always done one Wed, therefore +2 = Friday)
But it doesn't work.
Any help would be greatly appreciated!
Does the C:\Users\username folder actually exist? You will probably have to change username to your own username, or use Environ$("Username") like this:
"C:\Users\" & Environ$("Username") & "\Desktop\Temp\File"
And make sure the folder exists too, or you will get another error.
Also, use DateAdd() to add days:
NewDate = DateAdd("d", 2, Date)
And Format$() to format it (Text() is more of a worksheet function)
Once completed, you end up with this:
ActiveWorkbook.SaveAs Filename:= _
"C:\Users\" & Environ$("Username") & "\Desktop\Temp\File" & _
Format$(DateAdd("d", 2, Date), "mdyy") & ".txt" _
, FileFormat:=xlText, CreateBackup:=False

How do i save as pdf via VBA

I have a code, where I want to:
Save Masterfile (current active workbook),
amend the workbook and delete sheets,
then save separate copies of the edited workbook
as an Excel sheet and a PDF file.
The problem I have here is that the code saves the PDF file as the original Masterfile even after I have tried to activate the edited Excel file. Any help here? Would really appreciate any advice! Code below:
ActiveWorkbook.Save
Sheets("Inventory").Select
Cells.Select
Selection.Copy
Cells.Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.DisplayAlerts = False
Sheets("May").Select
Cells.Select
Selection.Copy
Cells.Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
Sheets("Macro").Select
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = False
Sheets("Oct").Select
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = False
Sheets("Inventory").Select
Range("A1").Select
Sheets("Inventory").Cells.Interior.ColorIndex = 0
ChDir "G:\9Fixed\Posi\2016\Inventory"
ActiveWorkbook.SaveAs Filename:= _
"G:\9Fixed\Posi\2016\Inventory\Asia Fixed - " & Format(Date, "dd mmm") & ".xls", FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
Application.DisplayAlerts = False
'ActiveWorkbook.ExclusiveAccess
Application.DisplayAlerts = True
Workbooks("Asia - " & Format(Date, "dd mmm") & ".xls").Activate
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"G:\9Fixed Income\Positions\2016\Inventory\Asia Fixed Income - " & Format(Date, "dd mmm") & ".pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
I could not reproduce the issue you were having.
Here is my 'test' code, using a workbook with 4 sheets and information in cells(1,1), one sheet named "May" --- which is deleted, and the new file does not have "May" and the pdf does not either.
I moved the saveas code towards the top of the file. Maybe that will fix your issue, but I don't believe it will.
Option Explicit
Sub SaveCopies()
Dim c_OUTPUTDIR As String
Dim sFileName As String
Dim fso As Object ' Used to handle paths, filenames, etc.
Set fso = CreateObject("Scripting.FileSystemObject")
c_OUTPUTDIR = "C:\temp\"
' Save the master copy.
ActiveWorkbook.Save
' Generate new name for file.
sFileName = fso.GetBaseName(ActiveWorkbook.FullName) & "_" & Format(Date, "dd mmm")
' Save new working file.
ActiveWorkbook.SaveAs Filename:= _
c_OUTPUTDIR & sFileName & ".xls", FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
' Make changes to working file.
Application.DisplayAlerts = False
ActiveWorkbook.Sheets("May").Delete
Application.DisplayAlerts = True
' Save the changes.
ActiveWorkbook.Save
' Save a PDF of the file.
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
c_OUTPUTDIR & sFileName & ".pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub

Prompt the file name from the cell value

I am placing a button on an Excel sheet which would save as the current worksheet to a separate file. Following is the code I am using:
Sub SaveWorkbook()
ActiveSheet.Copy
ActiveWorkbook.SaveAs Filename:= _
"C:\Users\username\Downloads\New folder" & ActiveSheet.Name & ".xlsx", FileFormat:= _
xlExcel8, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
, CreateBackup:=False
End Sub
Here instead of sheet name (ActiveSheet.Name), I want to place the text from the cell (D2:E2, both the cells are merged).
Is it possible to do?
Also here I have explicitly mentioned the path.
Is it possible to make it prompt to choose the path to save it?
While choosing the path, the name can be taken from the cell?
Update:
Sub SelectFolder()
Dim diaFolder As FileDialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Show
ActiveSheet.Copy
ActiveWorkbook.SaveAs Filename:= _
diaFolder & ActiveSheet.[d2] & ".xlsx", FileFormat:= _
xlExcel8, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
, CreateBackup:=False
Set diaFolder = Nothing
End Sub
Can you see what is the mistake here? the file is not saving in the selected path.
Replace ActiveSheet.Name with ActiveSheet.[d2] .
That will pull the value from the merged cell.
As far as getting the path from the user, it easy with:
Application.FileDialog(msoFileDialogFolderPicker)
https://stackoverflow.com/a/5975453/3566998

Excel VBA Index/Match function not working when indexing another workbook

I have a template that fills certain cells with sales data from another workbook but the other workbook has a new name for each month. When I try to assign a variable as the workbook name so that it finds it each time, I can't get the index/match function to work. Not sure where the error is but is the point where the VBA script fails...
Sub GetNetSales()
Dim Period As String
Dim NS As Workbook
Dim Can As Workbook
Dim BookName As String
Period = Range("Per").Value
Set Can = ThisWorkbook
ChDir "C:\Users\dlibby\Documents\" & Period
Workbooks.Open Filename:= _
"C:\Users\dlibby\Documents\" & Period & "\Net Sales " & Period & ".xlsx"
Set NS = ThisWorkbook
Can.Activate
Range("C10").Select
ActiveCell = _
Application.IfError(Application.Index(NS.Sheets("CM Sales").Columns("E:E"), Application.Match(Can.Range("H10").Value, NS.Sheets("CM Sales").Columns("A:A"), 0)), 0).Value
Range("C10").Select
Selection.Copy
Range("C11:C12").Select
ActiveSheet.Paste
Range("C16:C22").Select
ActiveSheet.Paste
Application.Calculate
Range("C10:C12").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("C16:C22").Select
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
When I am using Index/Match in Macro I am typing formula like this:
Folder = Sheets("Overview").Range("F4")
filename = Sheets("Overview").Range("G4")
filetype = Sheets("Overview").Range("H4")
tabname = Sheets("Overview").Range("I4")
style = Sheets("Overview").Range("J4")
SAPsizecode = Sheets("Overview").Range("K4")
ActiveCell.Formula = "=INDEX('" & Folder & "\[" & filename & filetype & "]" & tabname & "'!$" & SAPsizecode & ":$" & SAPsizecode & ",MATCH(C2,'" & Folder & "\[" & filename & filetype & "]" & tabname & "'!$" & style & ":$" & style & ",0))"
And this works for me. I think the problem in your code is how you are assigning the workbooks. With the approach above you don't need to open another workbook.

Issue with Saving Active Sheet to New workBook

I am trying to save an Active sheet in Excel using following VBA:
Application.CutCopyMode = False
FName = "C:\Users\Public\Documents\DTMForGIS\DTMtoGIS" & Format(Now, "yyyy-mm-dd hh_mm_ss") & ".xls"
ActiveWorkbook.SaveAs Filename:=FName, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled
Activeworkbook.close
but I am having two issues here:
1- When I want to open the file I am encountring with following Message:
Manually opening the file is OK by pressing the Yes but I am going to use the Excel File in GIS software which causing problem because of misunderstanding of format. As you can see it has .xls format
2- the Activeworkbook.close is not functioning since I have to close the Application after running the code by my own!
The first part is very important for me, to understand why this is happening? can you please let me know why?
You are using the wrong file format.
For .xls it is xlExcel8. xlOpenXMLWorkbookMacroEnabled is for .xlsm
Either use this
FName = "C:\Users\Public\Documents\DTMForGIS\DTMtoGIS" & _
Format(Now, "yyyy-mm-dd hh_mm_ss") & ".xls"
ActiveWorkbook.SaveAs Filename:=FName, _
FileFormat:=xlExcel8
or use this
FName = "C:\Users\Public\Documents\DTMForGIS\DTMtoGIS" & _
Format(Now, "yyyy-mm-dd hh_mm_ss") & ".xlsm"
ActiveWorkbook.SaveAs Filename:=FName, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled
Regarding your 2nd question. Change your code to this
Application.DisplayAlerts = False
FName = "C:\Users\Public\Documents\DTMForGIS\DTMtoGIS" & _
Format(Now, "yyyy-mm-dd hh_mm_ss") & ".xls"
ActiveWorkbook.SaveAs Filename:=FName, FileFormat:=xlExcel8
With ActiveSheet.UsedRange
.Copy
.PasteSpecial xlValues
.PasteSpecial xlFormats
End With
Application.Quit