Excel macro is diplaying 'Run-time error '1004' - excel

I understand there are many other threads for this but I don't know VBA code that well and I can't seem to understand the solutions provided. I been able to copy an existing macro from the web and use it on my computer with Excel 2013 fine, but once I try it on another computer with 2003 I get this error pop up. (Run-time error '1004' Method 'SaveAs' of object'_Workbook' failed) Would someone be able to let me know what I need to change in the code?
Sub ConvertToXlsx()
Dim strPath As String
Dim strFile As String
Dim wbk As Workbook
' Path must end in trailing backslash
strPath = "T:\"
strFile = Dir(strPath & "*.xls")
Application.DisplayAlerts = False
Do While strFile <> ""
If Right(strFile, 3) = "xls" Then
Set wbk = Workbooks.Open(Filename:=strPath & strFile)
wbk.SaveAs Filename:=strPath & strFile & "x", _
FileFormat:=xlOpenXMLWorkbook
wbk.Close SaveChanges:=False
End If
strFile = Dir
Loop
Application.DisplayAlerts = True
End Sub

The issue is here:
FileFormat:=xlOpenXMLWorkbook.
Excel 2003 does not recognize (nor have) the xlOpenXMLWorkbook file format.
xlExcel8 should work. Directly from the link:
These are the main file formats in Excel 2007:
51 = xlOpenXMLWorkbook (without macro’s in 2007, .xlsx)
52 = xlOpenXMLWorkbookMacroEnabled (with or without macro’s in 2007, .xlsm)
50 = xlExcel12 (Excel Binary Workbook in 2007 with or without macro’s, .xlsb)
56 = xlExcel8 (97-2003 format in Excel 2007, .xls)

Related

code works in office 2010 and 2016 but doesnt work in office 2007 [duplicate]

This question already has answers here:
vba excel 2010 Environ("username") not working in saveas filepath
(4 answers)
Closed 2 years ago.
Can someone please help, as the following code to save file both in excel and pdf format works in office 2016 but does not work on office 2007. can someone please modify the following code for me so that it can also work in office 2007.
Sub Button3_Click()
Dim Path As String
Dim filename As String
On Error GoTo Err_Clear
Path = Environ("USERPROFILE") & "\Desktop\rohailnisar\"
filename = Range("A1")
ActiveWorkbook.SaveAs filename:=Path & filename, FileFormat:=xlOpenXMLWorkbookMacroEnabled
Dim strFilename As String
Dim rngRange As Range
'Considering Sheet1 to be where you need to pick file name
Set rngRange = Worksheets("MIRCALCULATION").Range("A1")
Worksheets("MIRCALCULATION").PageSetup.PrintArea = "c1:u45"
Worksheets("LOAD").PageSetup.PrintArea = "c1:u45"
Worksheets("DR").PageSetup.PrintArea = "c1:J45"
Worksheets("MINUS").PageSetup.PrintArea = "B1:I25"
Sheets(Array("MIRCALCULATION", "DR", "MINUS", "LOAD")).Select
Sheets("MIRCALCULATION").Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, IgnorePrintAreas:=False, filename:=Path & filename
Err_Clear:
If Err <> 0 Then
MkDir CreateObject("wscript.shell").specialfolders("desktop") & "\rohailnisar"
Path = Environ("USERPROFILE") & "\Desktop\rohailnisar\"
filename = Range("A1")
ActiveWorkbook.SaveAs filename:=Path & filename, FileFormat:=xlOpenXMLWorkbookMacroEnabled
'Considering Sheet1 to be where you need to pick file name
Set rngRange = Worksheets("MIRCALCULATION").Range("A1")
Worksheets("MIRCALCULATION").PageSetup.PrintArea = "c1:u45"
Worksheets("LOAD").PageSetup.PrintArea = "c1:u45"
Worksheets("DR").PageSetup.PrintArea = "c1:J45"
Worksheets("MINUS").PageSetup.PrintArea = "B1:I25"
Sheets(Array("MIRCALCULATION", "DR", "MINUS", "LOAD")).Select
Sheets("MIRCALCULATION").Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:=Path & filename
End If
Sheets("MIRCALCULATION").Select
End Sub
i can run above code in office 365, but when i try to run the same code it gives me path error on office 2007. most people who will be using this code are on office 2007. so i really need this code to work in office 2007. this basically converts excel sheets into pdf and saves it along with excel file.
Try to remove the last escape character...
Path = Environ("USERPROFILE") & "\Desktop\rohailnisar

VBA Unable to open backup file containing dynamic name

New to VBA, no previous coding experience.
I am creating a backup copy using SaveCopyAs to change the extension to a .xlsx due to issues with the macro running in the new file. This code can create the backup file correctly, but when I try to open this new file I receive a Run-time error '1004' Method 'Open' of object 'Workbooks' failed.
I have tried writing this several different ways with no luck. I assume the dynamic component of this is causing the issue. Please advise what needs to be done to open the new file.
Sub Refresh()
Dim currwbk As Workbook
Dim FilePath As String
Dim newFileName As String
FilePath = ThisWorkbook.Path
T = Format(Now, "mmm dd yyyy hh mm ss")
Set currwbk = Workbooks("467_Report_Active.xlsm")
Application.ScreenUpdating = False
newFileName = FilePath & " " & T & ".xlsx"
Application.DisplayAlerts = False
currwbk.SaveCopyAs newFileName
Application.DisplayAlerts = True
Workbooks.Open (newFileName)
End Sub
Instead of SaveCopyAs use SaveAs along with extension code. I tried this and it worked for me.
File format code:
51 = xlOpenXMLWorkbook (without macro's in 2007-2016, xlsx)
52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2016, xlsm)
50 = xlExcel12 (Excel Binary Workbook in 2007-2016 with or without macro's, xlsb)
56 = xlExcel8 (97-2003 format in Excel 2007-2016, xls)
Reference link:
CODE:
Sub Refresh()
Dim currwbk As Workbook
Dim FilePath As String
Dim newFileName As String
FilePath = ThisWorkbook.Path
T = Format(Now, "mmm dd yyyy hh mm ss")
Set currwbk = Workbooks("467_Report_Active.xlsm")
Application.ScreenUpdating = False
newFileName = FilePath & " " & T & ".xlsx"
Application.DisplayAlerts = False
currwbk.SaveAs Filename:=newFileName, FileFormat:=51
Application.DisplayAlerts = True
Workbooks.Open (newFileName)
End Sub
Also, instead of using the actual filename in Set currwbk = Workbooks("467_Report_Active.xlsm"), you can simply assign thisworkbook object Set currwbk = Thisworkbook so that you don't need to update the filename, if there is a change in future.
EDIT: If you want your source workbook to be in open state even after saving and opening it with a new file name- check this stackoverflow discussion for the code.

SaveAs OK in excel 2013 but ignores filename in 2003

I have a code in excel VBA that saves a workbook with a coded path and filename which works perfectly on my computer at home running windows 8 and office 2013.
When I try to use it on my work computer which runs windows XP and office 2003 it ignores the coded path and file name and opens the save as dialogue box which defaults to the My Documents directory.
The intent is for the users at work to click save and the file will automatically go to a network drive with a personalised filename. They should not have to select a path or filename.
I have been testing with the path C:\Temp\ and saving a plain .XLS file which should work on both versions of Excel.
I tried it without disabling alerts and it gave no clues as to why it ignores the path and filename. I have also tried fileformat:=xlnormal etc. with no luck.
Why is this happening and how do I fix it?
Here is the code:
Sub FeedBackSave()
' Save the Feedback worksheet created by the user to the network drive using the path copied from
' the Management workhseet cell A11, the resource name copied from cell A1 and todays date as the filename.
Dim wsh As Worksheet
Dim nme, pth, TodaysDate As String
TodaysDate = format(Now, "dd-mm-yy")
nme = Range("A1").Value
pth = Worksheets("Management").Range("A11").Value
Application.ScreenUpdating = False
Application.DisplayAlerts = False ' Prevents alerts like incorrect file type or overwrite file y/n to permit 1 click save
'Save Feedback worksheet
ActiveWorkbook.Close SaveChanges:=True, Filename:=pth & "FeedBack " & nme & " " & TodaysDate & ".xls"
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Saveas Before you close the workbook, might help., check the ranges, not sure if they are on the same sheet or not.
Sub FeedBackSave()
' Save the Feedback worksheet created by the user to the network drive using the path copied from
' the Management workhseet cell A11, the resource name copied from cell A1 and todays date as the filename.
Dim wsh As Worksheet
Dim nme As String, pth As String, TodaysDate As String, FName As String
Set ws = Worksheets("Management")
TodaysDate = Format(Now, "dd-mm-yy")
nme = Range("A1").Value
pth = ws.Range("A11").Value
FName = pth & nme & "-" & TodaysDate & ".xls"
Application.DisplayAlerts = 0
With ActiveWorkbook
.SaveAs FileName:=FName
.Close
End With
End Sub

Is there an alternative to Scripting.FileSystemObject in Excel 2011 VBA for the mac?

The answers to How can I install/use “Scripting.FileSystemObject” in Excel 2011 for MAC? seem to indicate that using Scripting.FileSystemObject in Excel 2010 for the mac is not possible.
What other alternative is available so I can:
get a collection of all Excel files in a specific directory
iterate through each worksheet within each file and export it to a .csv file
Currently this is a six-step process for each file:
--how to create CSV files for all worksheets in a file:
1. open file
2. click "Developer"
3. click editor
4. click ThisWorkbook
5. copy in:
Sub save_all_csv()
On Error Resume Next
Dim ExcelFileName As String
ExcelFileName = ThisWorkbook.Name
For Each objWorksheet In ThisWorkbook.Worksheets
Filename = "FILE-" & ExcelFileName & "-WORKSHEET-" & objWorksheet.Name & ".csv"
objWorksheet.SaveAs Filename:="Macintosh HD:Users:edward:Documents:temporaryNoBackup:" & Filename, FileFormat:=xlCSV, CreateBackup:=False
Next
Application.DisplayAlerts = False
Application.Quit
End Sub
6. click run (it closes by itself)
I'm looking for a way to automate this on the Mac, ideally, a (cron job?, service?) would open the excel file every 10 minutes, which would in turn look in a directory, convert all the other Excel files to .csv files, and then close by itself.
Without Scripting.FileSystemObject, how can I make this Excel-to-CSV conversion fully automatic on the Mac?
The only way I can think of is using the "Dir" function. Since mac supports extra characters in their filenames, wildcards do not work with the "Dir" function. Here is a sample.
Function GetFileList(folderPath As String) As Collection
'mac vba does not support wildcards in DIR function
Dim file As String
Dim returnCollection As New Collection
If Right$(folderPath, 1) <> "/" Then
folderPath = folderPath & "/"
End If
file = Dir$(folderPath) 'setup initial file
Do While Len(file)
returnCollection.Add folderPath & file
file = Dir$
Loop
Set GetFileList = returnCollection
End Function
You can put the VBA in an add-in (.xlam file) that is attached to Excel itself, rather than the workbook. For your example code, the only modification would be to write against ActiveWorkbook instead of ThisWorkbook.
Sub save_all_csv()
On Error Resume Next
Dim ExcelFileName As String
ExcelFileName = ActiveWorkbook.Name
For Each objWorksheet In ActiveWorkbook.Worksheets
Filename = "FILE-" & ExcelFileName & "-WORKSHEET-" & objWorksheet.Name & ".csv"
objWorksheet.SaveAs Filename:="Macintosh HD:Users:edward:Documents:temporaryNoBackup:" & Filename, FileFormat:=xlCSV, CreateBackup:=False
Next
Application.DisplayAlerts = False
Application.Quit
End Sub
You can also leverage auto_open() to automate binding a hotkey. Once that's done, you can just open a workbook, press a hotkey, and get your CSV files.
Public Sub auto_open()
' Register hotkeys
' See key codes here
' https://msdn.microsoft.com/en-us/vba/excel-vba/articles/application-onkey-method-excel
' ^ = CTRL
' % = ALT
' + = SHIFT
Application.OnKey "^+e", "save_all_csv" ' Ctrl+Shift+E will call save_all_csv()
End Sub

How to automate converting Excel xls files to Excel xml format?

I have about 200 Excel files that are in standard Excel 2003 format.
I need them all to be saved as Excel xml - basically the same as opening each file and choosing Save As... and then choosing Save as type: XML Spreadsheet
Would you know any simple way of automating that task?
Here is a routine that will convert all files in a single directory that have a .xls extension.
It takes a straight forward approach. Any VBA code in a workbook is stripped out, the workbook is not saved with a .xlsm extension. Any incompatability warning are not dislayed, instead the changes are automatically accepted.
Sub Convert_xls_Files()
Dim strFile As String
Dim strPath As String
With Application
.EnableEvents = False
.DisplayAlerts = False
.ScreenUpdating = False
End With
'Turn off events, alerts & screen updating
strPath = "C:\temp\excel\"
strFile = Dir(strPath & "*.xls")
'Change the path as required
Do While strFile <> ""
Workbooks.Open (strPath & strFile)
strFile = Mid(strFile, 1, Len(strFile) - 4) & ".xlsx"
ActiveWorkbook.SaveAs Filename:=strPath & strFile, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close True
strFile = Dir
Loop
'Opens the Workbook, set the file name, save in new format and close workbook
With Application
.EnableEvents = True
.DisplayAlerts = True
.ScreenUpdating = True
End With
'Turn on events, alerts & screen updating
End Sub
You could adapt the code I posted here:
http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/04/01/loading-office-documents-in-net.aspx
It shows how to save as PDF (Word is shown in the blog, but if you download the solution, it has code for Excel and PPT).
You need to find the function for saving as the new format instead of exporting (probably the easiest way is to record a macro of yourself doing it in Excel and then looking at the code).
Open them all up, and then press ALT+F11 to get to macro editor and enter something like:
Sub SaveAllAsXml()
Dim wbk As Workbook
For Each wbk In Application.Workbooks
wbk.SaveAs FileFormat:=XlFileFormat.xlXMLSpreadsheet
Next
End Sub
And then press F5 to run it. May need some tweaking as I haven't tested it.
Sounds like a job for my favorite-most-underrated language of all time: VBScript!!Put this in a text file, and make the extension ".vbs":
set xlapp = CreateObject("Excel.Application")
set fso = CreateObject("scripting.filesystemobject")
set myfolder = fso.GetFolder("YOURFOLDERPATHHERE")
set myfiles = myfolder.Files
for each f in myfiles
set mybook = xlapp.Workbooks.Open(f.Path)
mybook.SaveAs f.Name & ".xml", 47
mybook.Close
next
I haven't tested this, but it should work
The simplest way is to record macro for one file and then manually edit macros to do such actions for files in folder using loop. In macro you can use standart VB functions to get all files in directory and to filter them. You can look http://www.xtremevbtalk.com/archive/index.php/t-247211.html for additional information.
Const xlXLSX = 51
REM 51 = xlOpenXMLWorkbook (without macro's in 2007-2013, xlsx)
REM 52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2013, xlsm)
REM 50 = xlExcel12 (Excel Binary Workbook in 2007-2013 with or without macro's, xlsb)
REM 56 = xlExcel8 (97-2003 format in Excel 2007-2013, xls)
dim args
dim file
dim sFile
set args=wscript.arguments
dim wshell
Set wshell = CreateObject("WScript.Shell")
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open( wshell.CurrentDirectory&"\"&args(0))
objExcel.DisplayAlerts = FALSE
objExcel.Visible = FALSE
objWorkbook.SaveAs wshell.CurrentDirectory&"\"&args(1), xlXLSX
objExcel.Quit
Wscript.Quit

Resources