I have this macro which is updating some tables and it has been working fine for the past two weeks, however it suddenly started giving me 1004 runtime error - initially it was runtime error 1004 method saveas of object _workbook failedub SaveAs(), now it is simply Run Time Error 1004 “Application-Defined or Object-Defined Error.
I suspect is has something to do with saving the file as that's the point it gives me error, everything else works fine. I have separated the saving code in a different macro and its still giving this error.
I have tried to make the path string into one piece (Mth var is a variable we change each month of reporting and is fed off a sheet value but have had to add it manually for testing purpose). Initially Path and Filename missed the ("S") at the end as I thought the names might be conflicting with something in the library.
Please note, before the code was using ActiveWorkbook.Saveas and was working fine I am not sure it's a problem of Excel knowing which sheet or workbook to look at.
How do I fix this? Please see code below:
ThisWorkbook.Activate
Dim Mth As Integer
Mth = 4
Dim FileNames As String
Dim Paths As String
Dim Fullstring As String
Application.DisplayAlerts = False
Paths = "\\RL1VMFIL02\Finance$\Financial Management\SITES & SERVICES\Corporate\2020-21\C - Statements & Trends" & "\M" & Mth & "\"
FileNames = Format(Now(), "dd.mm.yy") & " Budget Statement & Trend M" & Mth & " - " & Format(Now(), "hh.mm") & ".xlsm"
Fullstring = Paths & FileNames
ThisWorkbook.Activate
ThisWorkbook.SaveAs Fullstring
Application.DisplayAlerts = True
End Sub
This has been fixed by making sure the path folder exists as adviced by #RustyBucketBay & #GMalc.
Explicitly, the Month path included a 0 so it should've been either Mth var = '04 rather than 4 or path "\M0" & Mth & ""
Many thanks guys for the help!
Related
Here is my code.
My purpose is, open a test excel and then save as a filename contained within the 'Test' sheet. I simply want to automate the task of saving an Excel for each of a list of filenames.
Sub POPButton1_Click()
Dim i As Long, LastRow As Long
LastRow = Test.Range("A" & Rows.Count).End(xlUp).Row
Dim filename As String
filename = ThisWorkbook.Path & Application.PathSeparator & "Test.xlsx"
Dim sjk As Workbook
Set sjk = Workbooks.Open(filename)
Dim saveName As String
For i = 1 To LastRow
saveName = Test.Cells(i, "D").Value
sjk.SaveAs ThisWorkbook.Path & "\" & saveName
sjk.Close
Next i
End Sub
The first excel is saved just fine, then I hit the bug. -2147221080 Automation error.
The line of code that highlights on debug is:
sjk.SaveAs ThisWorkbook.Path & "\" & saveName
I have looked around on this site and many others, as it appears a common bug, and I get the feeling it is an easy fix, but nothing I have tried has worked. I have re-written the code many times to get it to this point - I just can't see where the error is...
Ah! I think the answer is that you close the file but then never re-open it.
Move your Set sjk = Workbooks.Open(filename) inside your For loop at the top.
That should fix it for you.
I am pulling information from worksheets that are in a folder - all files are using the same template - into another worksheet to create a matrix of the information.
I am only pulling three cells from each template and the first two are pulling correctly, because they are on one sheet of the template model but the third is not populating and I am receiving an error.(Run time error 1004. Method of Range of Object_global failed") I am not sure if that has anything to do with my error or if it's something occurring before then.
I have the following:
Private Function GetValuePrice(path, file, sheet, ref)
Dim arg As String
If Right(path, 1) <> "\" Then path = path & "\"
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xR1C1)
Debug.Assert Var = 0
GetValuePrice = ExecuteExcel4Macro(arg)
End Function
I am receiving an error and when I hit debug it shows me that ref is empty.
(Run time error 1004. Method of Range of Object_global failed")
This is the code i have in the button to pull from the tabs Workload and Project Info from the templates in the folder.
Private Sub CommandButton21_Click()
ThisWorkbook.Sheets("Sheet1").Range("a166:h500").ClearContents
ThisWorkbook.Sheets("Sheet1").Range("j166:v500").ClearContents
Application.Calculation = xlCalculationManual
ProjectInfo
WorkLoad
Application.Calculation = xlCalculationAutomatic
End Sub
I'm not sure what to fix because I run another matrix with the same code but change the file destination and it works.
In my second sub, i was not pulling the correct variable to display in the matrix. I had declared "CC" but was displaying "AA". Therefore changed the AA to CC and it worked.
This code has been working for months, and today it is throwing the error:
Run-Time Error '1004'
Method 'SaveAs' of Object '_Workbook' failed
The line of code causing the error is:
'~~>. Save the file
.SaveAs Filename:="\\MY\File\Path\Report_" & Format(Now(), "yyyymmdd") & ".xls", FileFormat:=53
I dont know what has changed here for this suddenly not to work, any ideas?
I am running MS Excel 2016, Version 1609
There is no file in that location with the same name.
I want to save as an .xls in case anyone we send this to has an older version of Excel, I could change it to an .xlsx and rewrite the code a bit but I am curious why all of the sudden this errored out?
Thanks for looking.
I think to save as ".xls", FileFormat should be 56
http://www.rondebruin.nl/win/s5/win001.htm
What you can do is to use the macro recorder for this. This is what mine produces:
ChDir "C:\Users\gropc\Desktop"
ActiveWorkbook.SaveAs Filename:="C:\Users\uname\Desktop\Book1.xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
The format should be taken into account.
if it's a hidden file issue you could exploit FileSystemObject object and loop until you find a "free" file name
so your code line could become the following:
.SaveAs fileName:=GetFreeFileName("\\MY\File\Path\Report_" & Format(Now(), "yyyymmdd"), ".xls")
which uses the following function:
Function GetFreeFileName(fileName As String, fileExt As String)
Dim iFile As Long
With CreateObject("FileSystemObject")
Do While .FileExists(fileName & fileExt)
iFile = iFile + 1
fileName = fileName & "-" & iFile
Loop
End With
End Function
I have some code which looks for a value with a given sheet name in two separate workbooks.
What I want to do is when the first workbook does not have the sheet, instead of the following prompt coming up, it cancels/throws an error and using the error handling goes to the second spreadsheet. How do I do this?
Currently I am using this code to achieve this:
fFormString1 = "'" & wkBookRef1 & firstShtName & "'!$L$6/1000"
fFormString2 = "'" & wkBookRef2 & firstShtName & "'!$L$6/1000"
Application.DisplayAlerts = False 'Does nothing to the prompt
On Error GoTo tryTwo 'Following only throws error when prompt is canceled
ThisWorkbook.Sheets("Place").Range("E53").Formula = "=" & fFormString1
GoTo endTen
tryTwo:
ThisWorkbook.Sheets("Place").Range("E53").Formula = "=IFERROR(" & fFormString2 & ","""")"
On Error Resume Next
endTen:
Application.DisplayAlerts = True 'Does nothing to the prompt
Note: I wish to do this with the spreadsheet closed ideally. Or visually not present to improve speed and smoothness of operation for my client.
ExecuteExcel4Macro will return a value from a closed workbook. If the worksheet doesn't exist it will throw an error 1004 'A formula in this worksheet contains one or more invalid references.
ExternalWorksheetExists uses this to test it the worksheet exist.
Function ExternalWorksheetExists(FilePath As String, FileName As String, WorksheetName As String) As Boolean
If Right(FilePath, 1) <> "\" Then FilePath = FilePath & "\"
On Error Resume Next
Call ExecuteExcel4Macro("'" & FilePath & "[" & FileName & "]" & WorksheetName & "'!R3C3")
ExternalWorksheetExists = Err.Number = 0
On Error GoTo 0
End Function
When using ExecuteExcel4Macro, all references must be given as R1C1 strings. Here is an example of a valid string:
ExecuteExcel4Macro("'C:\Users\tinzina\Documents\[Book1.xlsm]Sheet1'!R6C12")
Borrowing heavily from Thomas' answer (full credit is due). However it seems that this didn't work for you.
Use ExecuteExcel4Macro but ascribe the value to the variable val. Then check if this is the error you are looking for Error(2023).
Please find the code below:
'Check if the sheet exists in the workbook, used to check which forecast file one should look in
Function ExtSheetExists(formString) As Boolean 'Form string is a formula string with both the worksheet and the workbook
Dim val As Variant
'Tries to execute formula and throws error if it doesn't exist
On Error Resume Next
val = ExecuteExcel4Macro(formString)
ExtSheetExists = (val <> Error(2023)) 'Returns False if the sheet does not exist based on Error 2023
On Error GoTo 0
End Function
I created a command button that auto saves the workbook into one of two file paths depending on info in the spreadsheet. This works fine for me but my colleague is gettting the follwing error everytime.
The method is extending the file path and adding \0BA1700 in this instance (this changes every time). This doesn't happen on my computer and the code works as it should. Here is the sub:
Private Sub CommandButton21_Click()
Dim pathUnder As String
Dim pathOver As String
Dim file As String
file = Range("D2").Value
pathUnder = "G:\Technical Services\LARGE CORPORATE UW\Full Insurance\FI Quote Spreadsheets (below 500)\"
pathOver = "G:\Technical Services\LARGE CORPORATE UW\Full Insurance\FI Quote Spreadsheets (above 500)\"
If Range("D4").Value = "" Or Range("D2").Value = "" Then
MsgBox ("Save Failed. Please ensure there are values in both cells D2 and D4")
Else
If Range("D4").Value >= 500 Then
ActiveWorkbook.SaveAs fileName:=pathOver & file & ".xlsm", FileFormat:=52
Else
ActiveWorkbook.SaveAs fileName:=pathUnder & file & ".xlsm", FileFormat:=52
End If
End If
End Sub
Help much appreciated.
Maybe some kind of exception? Are you sure nothing is currently using this file? Maybe you own program does?
Solved. My colleague's computer didn't have the G drive mapped to the correct server so remapped it and now working fine.