So the code below functioned with out any issues before. Basically, I get this doc emailed to me, the code runs to extract the needed data, saves to the workbook to the specified file pathway to the specified filename, and the next part of the code puts all the data gathered on a summary doc.
Today, I tried to add an alert message box so that if certain conditions were met , a message to the user would be provided when there was an attempt to save. When I did that, I began getting a Runtime 1004 error and still get it even though I have removed the beforesave event on the worksheet. It was using ActiveWorkbook... and then I changed it to ThisWorkbook after reading about how ActiveWorkbook can cause errors.
I don't know what the file name will be when I get these docs, and would like to simply have the doc save and apply to specified file name when I run the macro. Any ideas on why I am suddenly getting this error?
'saves incident report to incident report folder
ThisWorkbook.SaveAs Filename:=("C:\Users\ashley.graham\Field Agent Folder\Incident Reports\Test folder\Test Incident report folder\" & IncidentReport & AgentName & ".xlsm")
Try adding this:
Dim wb As Workbook
Set wb = Workbooks(ActiveWorkbook.Name)
wb.SaveAs Filename:=("C:\Users\ashley.graham\Field Agent Folder\Incident Reports\Test folder\Test Incident report folder\" & IncidentReport & AgentName & ".xlsm")
Related
So I work for a company that's a bit slow with the times and manually requires workers to input sales data into a spreadsheet at end of day. I was tired of that so I created a separate VBA Excel program to automate it.
It has been working fine for the past two months but for seemingly no reason it seems to of corrupted the spreadsheet it was altering when I ran my program recently. Attempting to open the spreadsheet and enabling macros on the work PC causes Excel (2013) to crash. Opening other worksheets and enabling macros on them works fine though.
I tried emailing it to myself to figure out why but it opens correctly and with no issues with my version of Excel (Office 365)
I know that the corruption must of occurred either before my program ran or just after it started running because it performs a backup of the spreadsheet before altering/inputting any data and the backup is also corrupted on the work pc.
To try and simplify a hundred lines of code and 5 helper functions or so; it opens the files needed with Workbooks.Open (ThisWorkbook.path & "\" & file) where file is just the name of the workbook to be altered; it then performs a backup and deletes backups older than 7 days.
Here's the generic backup code:
Private Sub deleteBackup(folderName As String)
Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
For Each fcount In FSO.GetFolder(ThisWorkbook.path & folderName).Files
If DateDiff("d", fcount.DateLastModified, Now()) > 7 Then
Kill fcount
End If
Next fcount
End Sub
Private Sub backup(fileName As String)
Dim Monthly As Workbook
Dim dateStamp As String
dateStamp = Format(returnDailyDate(), "dd.mm.yyyy")
' Check if folders exist, if they don't, create them
If Dir(ThisWorkbook.path & BackupPath, vbDirectory) = vbNullString Then
MkDir (ThisWorkbook.path & BackupPath)
End If
Set Monthly = Workbooks(MonthlyPath)
Monthly.Save
Set FileSystemObject = CreateObject("Scripting.FileSystemObject")
FileSystemObject.CopyFile ThisWorkbook.path & "\" & MonthlyPath, ThisWorkbook.path & BackupPath & fileName & dateStamp & FileExtension
End Sub
Is there a logical reason for why this would happen or why it wouldn't work in 2013 but does in 365?
idk if it was a random inevitable hiccup involving running out of memory or something (let's just say the works dev department isn't the greatest) or whether my program caused the corruption and could potentially do it again in the future.
Thanks for your time.
Update:
So sending the workbook that was opened by office 365 and worked in 365; back to the work PC and it works fine now. So I assume 365 has better error correction than 2013, but I still have no idea what caused the error in the first place.
Using Excel 2010 on Windows 7. I have a VBA macro that saves the first worksheet of an excel workbook (.xlsm) into a CSV file. This had mostly worked in the past. Recently, I get error messages per the picture below, which state "Run-time error '1004': Microsoft Excel cannot open or save any more documents because there is not enough available memory or disk space."
So a couple things:
A common suggested solution from my Google searching is to set the file's location as a Trusted Location. This did not work.
I have enough disk space. That can't be the issue.
I'm not sure exactly what is meant by "available memory," but if it in any way refers to the Physical Memory figure listed in Windows Task Manager, that figure is 75%. The ultimate CSV file itself tends to be about 1,500KB.
I am always able to save this worksheet as a CSV manually without encountering any error messages, but when I do it via this VBA macro, I get the error message.
Picture of error message
My excel VBA save-as-CSV macro:
Sub saveAsCSV()
Application.DisplayAlerts = False
ThisWorkbook.Sheets("Sheet1").Copy
ActiveWorkbook.SaveAs Filename:="dummyfilename.csv", FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
Try this, you don't have to use Copy or Activate. If your code is in the workbook that you want to save as a workbook you can use ThisWorkbook. Kudos to #Variatus for identifying need for a path.
ThisWorkbook.Sheets("Sheet1").SaveAs ThisWorkbook.Path & "/" & "dummyfilename" & ".csv", FileFormat:=6
I have an inventory xls file, that includes a diagram of the office. When the xls is opened, the VBA automatically makes a backup of the file before any changes are made. That has worked for the past year. Today it has broken.
Yesterday, the file was working fine.
1) I added some info to the xls sheet - nothing unusual; the same sort of info I've added over the past year. I did NOT edit the VBA.
2) I added some objects (shapes-circle, square, etc) to the tab with the office diagram.
Today, the file is not working.
1) The VBA debugger gives an error on open: "Compile Error: Cannot find file or library."
2) Numerous text boxes/shapes have vanished off the tab with the diagram. I did not remove them.
UPDATE 1: I moved a shape on the diagram, and all the text boxes reappeared.
Any suggestions to fix this are appreciated.
'Saves an exact copy of the file upon opening it to the \Back_Tracker location and added today's date to the filename.
Private Sub Workbook_Open()
Dim WBPath As String, WBName As String, TimeStampStr As String, PassW As String
WBPath = ThisWorkbook.Path
WBName = ThisWorkbook.Name
'PassW = "something"
Const cstrBACKUP As String = "Backup_Tracker"
If InStr(1, WBPath, cstrBACKUP) = 0 Then 'prevent backups from making backups of themselves.
TimeStampStr = Format(Now(), "YYYY-MM-DD_hh-mm_")
'Application.StatusBar = "Saving backup..."
ActiveWorkbook.SaveCopyAs Filename:=WBPath & Application.PathSeparator & cstrBACKUP & Application.PathSeparator & TimeStampStr & WBName
'Application.DisplayStatusBar = False
'Application.DisplayStatusBar = True
End If
End Sub
My experience with Excel VBA is that the code can sometimes corrupt when opening. It used to be the case with Access as well, but I'm not sure if that was eventually fixed.
My solution was to either make backup copies after each edit, or use source control for the Excel file. Its the only way to be sure.
Found the problem.
Unchecked this, and it's working now.
Reference
Open the database or application.
Open a module in Design view or press ALT+F11 to switch to the Visual Basic Editor.
On the Tools menu, click References.
Clear the check box for the type library or object library marked as "Missing:"
Users have an Excel spreadsheet. To save it, they press a button which runs the below VBA code.
The code attempts to save the Excel spreadsheet to a network location amending the file name with today's date.
Intermittently the code will fail with
"Run-time error '1004': Method 'SaveAs' of object'_Workbook' failed".
The script is:
Public Sub Copy_Save_R2()
Dim wbNew As Workbook
Dim fDate As Date
fDate = Worksheets("Update").Range("D3").Value
Set wbNew = ActiveWorkbook
With wbNew
ActiveWorkbook.SaveAs Filename:="Q:\R2 Portfolio Prints\#Archive - R2 Portfolio\" & "R2 Portfolio - CEC A " & Format(fDate, "mm-dd-yyyy")
End With
Sheets("Update").Activate
End Sub
As Hugo stated, it could be an issue with the mapped drive. I prefer to use the full UNC path (\\Thismachine\...), in case the workbook gets used on a machine that doesn't have the mapped drive set up.
I thought the missing extension could be the problem, but I just tested it in Excel 2013 and it automatically added .xlsx to the filename.
The issue is probably due to the wbNew reference. It's completely unnecessary and should not be combined with ActiveWorkbook. Basically, you should have either a reference to a workbook, or use the predefined ActiveWorkbook reference. I'd also recommend using ThisWorkbook instead, since the user might click on another book while code is running.
Public Sub Copy_Save_R2()
Dim wbNew As Workbook
Dim fDate As Date
fDate = Worksheets("Update").Range("D3").Value
Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:="Q:\R2 Portfolio Prints\#Archive - R2 Portfolio\R2 Portfolio - CEC A " & Format(fDate, "mm-dd-yyyy") & ".xlsx"
Application.DisplayAlerts = True
ThisWorkbook.Sheets("Update").Activate
End Sub
Edit: Added Application.DisplayAlerts commands to prevent any Save popups, such as using .xlsx instead of .xlsm, and overwriting an existing copy.
Edit 2018-08-11: Added escape backslashes to fix UNC path display. Added strike-through to inaccurate statement about the With statement (see comments below). Basically, since nothing between With and End With begins with a ., the statement isn't doing anything at all.
I was also looking for the cause of this error, and then remembered I was working on a version of my spreadsheet that had been recovered. Once I manually saved the recovered file and reopened it there was no problem with the vba code to save the workbook.
When it happened to me, I added a command before the save.
On Error Resume Next
Kill TargetFullname
On Error GoTo 0
wb.SaveCopyAs TargetFullname
(I also use application.display=false)
Had the same error message when saving a workbook with a dynamic file name to a network location. Saving stage suddenly stopped working. Error 1004 Workbook SaveAs method failed.
Realised after a while that the location where the macro saved the output had changed and the macro's script had been tweaked by the team to reflect the new network address.
Whilst the new network address was accurate, it was simply too long...
I shortened the folder names, as well as the file name and bingo... Workbooks are being saved again, with no error messages.
This worked for me. Ensure your workbook is not shared. I guess "Shared" workbooks have limitations.
Saw this here:
https://www.ozgrid.com/forum/forum/help-forums/excel-general/27843-save-xls-as-txt
In the "Review" tab click "Share Workbook" and ensure "Allow changes by more than one user at the same time. This allows workbook merging" is unchecked.
I'm keeping sets of interrelated Excel 2003 spreadsheets for each of my company's projects.
I want to copy some template XLS files to the project name and change the links that connect them to each other.
For example, the file TEMPLATE_ScanProgress.xls links to TEMPLATE_Film_Review.xls.
I am copying them both to 123456_ScanProgress.xls and 123456_Film_Review.xls, and updating the link in 123456_ScanProgress.xls.
Sample code of what I'm doing:
If Dir("WorkOrder & "_ScanProgress.xls") = "" Then
FileCopy "TEMPLATE_ScanProgress.xls", WorkOrder & "_ScanProgress.xls"
Workbooks.Open Filename:=WorkOrder & "_ScanProgress.xls", UpdateLinks:=0
ActiveWorkbook.ChangeLink "TEMPLATE_Film_Review.xls", _
WorkOrder & "_Film_Review.xls", _
xlLinkTypeExcelLinks
Workbooks(WorkOrder & "_ScanProgress.xls").Close SaveChanges:=True
Else
FileExists = True
FileExistsWarning_7 = WorkOrder & "_ScanProgress.xls"
End If
The problem is that when the code tries to update the link I get a file dialog asking me to choose a file for the change, even though I already specified which file I want in the code.
Try setting DisplayAlerts to False. DisplayAlerts is on the Application object and is used to suppress dialog boxes for example when overwriting a file. It may work in this case too.