vba to save as CSV - excel

I found code to save a single sheet as CSV.
But I am getting error:
Run-time error '1004'
Cannot access read-only document 'MasterCallOneList.CSV'
How to fix?
The document is actually a new document that does not exist, so I don't know why it would say that the document is read-only.
Application.DisplayAlerts = False
Dim strFullName As String
strFullName = Application.Path + "\MasterOneCallList.CSV"
ThisWorkbook.Sheets("Combined").Copy
ActiveWorkbook.SaveAs Filename:=strFullName, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True

Could be due to protection levels in the application.path directory.
Have you tried
Application.DisplayAlerts = False
Dim strFullName As String
strFullName = ThisWorkbook.Path + "\MasterOneCallList.CSV"
ThisWorkbook.Sheets("Combined").Copy
ActiveWorkbook.SaveAs Filename:=strFullName, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True

strFullName = Application.Path + "\MasterOneCallList.CSV"
This could be the error, the path name would be the ms_office excel folder. Try using an actual folder path string and the code should work. If it does work, you would have to figure a way to get an actual path string.
Sub Button1_Click()
Dim strFullName As String
Application.DisplayAlerts = False
strFullName = "C:\Users\dmorrison\Downloads\TestKryztof" + "\MasterOneCallList.CSV"
ThisWorkbook.Sheets("Combined").Copy
ActiveWorkbook.SaveAs Filename:=strFullName, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub

Related

Saving a marco enabled workbook into a file, need it to be non macro enabled

Im trying to save a file into a location which will then be used to run a report from.
Currently this code is saving the file as a macro enabled worksheet, I need it to be just a .xlsx
Sub SaveToDesktop()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
With ActiveWorkbook
.SaveAs "W:\Logistics\Distribution\Chep\Chep Dehire Master Control\In" & "\" & Format(Now, "hh-nn-ss-dd-mm-yyyy") & " " & ActiveWorkbook.Name
'.Close
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Thanks, file saved."
Application.Quit
End Sub
Any help or ideas would be greatly appreciated.
Thanks guys, problem solved!
Read through the guide and worked from karma's suggestion.
Sub Saveworkbook()
Dim Path As String
Dim Filename As String
Path = "W:\Logistics\Distribution\Chep\Chep Dehire Master Control\In\"
Filename = ActiveWorkbook.Name & Format(Now, "hh-nn-ss dd-mm-yyyy")
Application.DisplayAlerts = False
Application.ScreenUpdating = False
ActiveWorkbook.SaveAs Filename:=Path & Filename & ".xlsx", FileFormat:=51
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Thanks, file saved."
Application.Quit
End Sub

ActiveSheet.Copy

My company has had a Macro that has been running without change for the past two years. With the new Microsoft updates the code has been failing. The Macro has been designed to upload data from another document, re-arrange it, and then send it to a Sample Manager. The following code creates a run-time error '1004' Copy method of Worksheet class failed. When I hit debug ActiveSheet.Copy is highlighted. If anyone has any suggestions, it would help. The code is:
Sub ExportToLims()
Dim fname As String
Application.DisplayAlerts = False
Application.ScreenUpdating = False
fname = "X:\LIMS Integration Manager\Entech7200\Input\" & ActiveSheet.Name & "-" & Format(Now(), "mmddyy-hhmm") & ".csv"
ActiveSheet.Copy
ActiveWorkbook.SaveAs filename:=fname, FileFormat:=xlCSV
ActiveWorkbook.Close SaveChanges:=False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox ("Injection Report Exported to LIMS IM")
End Sub

How to save xlsm as xlsx?

I have a xslm file. I want to save the file as xlsx and email.
I am able to SaveCopyAs it as xls file. If I try to save it as xlsx, it does get saved but when I open it, it gives an error.
ActiveWorkbook.SaveCopyAs Filename:=ActiveWorkbook.Path & "\MyFileName - " & Format(Date, "mm-dd-yyyy") & ".xlsx"
Excel cannot open the file '...path\MyFileName.xlsx' because the file format or file extension is not valid. Verify that file has not been corrupted and that file extension matches the format of the file
SaveCopyAs does not change the file-type.
You simply cannot save a .xlsm as .xlsx via SaveCopyAs.
EDIT
a workaround is to save a copy which then is changed in type while the old copy will be deleted like:
Dim wb As Workbook, pstr As String
pstr = ActiveWorkbook.Path & "\MyFileName - " & Format(Date, "mm-dd-yyyy") & ".xlsm"
ActiveWorkbook.SaveCopyAs Filename:=y
Set wb = Workbooks.Open(pstr)
wb.SaveAs Left(pstr, Len(pstr) - 1) & "x", 52
wb.Close False
Kill pstr
Try this:
Sub SaveAsXLSX()
ThisWorkbook.Save 'Optional
Application.DisplayAlerts = False
ThisWorkbook.SaveAs ActiveWorkbook.Path & "\MyFileName - " & Format(Date, "mm-dd-yyyy"), 51 '51 = xlsx
Application.DisplayAlerts = True
ThisWorkbook.Close 'Optional
End Sub
All you need to do is SaveAs and change the file format to 51 (xlsx)
If you want to "Save a copy" - SaveAs does practically the same thing - the difference being your currently open file becomes the saved file, but you can simply reopen the old one if you wish and nothing changes.
What you actually want to do is SaveAs a different file type, so use SaveAs.
I This is more readable. TESTED.
Sub SaveXlsmAsXlsx()
Dim wb As Workbook, Filenamepath As String, Filenameext As String, Filenameonly As String, Filepathonly As String
Application.DisplayAlerts = False
Filenamepath = ActiveWorkbook.FullName
Filenameext = ActiveWorkbook.Name
Filenameonly = Replace(Filenameext, ".xlsm", "")
Filepathonly = Replace(Filenamepath, ".xlsm", "")
Set wb = Workbooks.Open(Filenamepath)
'51 = xlsx
wb.SaveAs Filename:=Filepathonly & "_" & Format(Date, "mm-dd-yyyy"), FileFormat:=51
wb.Close True
'Kill- Best not to kill anyone, you might be sorry
ThisWorkbook.Close SaveChanges:=True
Application.DisplayAlerts = True
End Sub
This code add to any module:
Public Sub XLSMtoXLSX(FaylAdi As String)
Dim FullPath As String
Dim wb As Workbook
MsgBox "YOU WILL GET A WARNING AFTER COMPLETED, PLEASE WAIT"
ThisWorkbook.Save
On Error GoTo XETA
'You can change the name of the folder path below
FullPath = "C:\kohne sistem\Excel\VBA\Anbar\temp\" & FaylAdi & ".xlsm"
ThisWorkbook.SaveCopyAs FullPath
Application.DisplayAlerts = False
Set wb = Workbooks.Open(FullPath)
wb.SaveAs Left(FullPath, Len(FullPath) - 1) & "x", 51
wb.Close False
Kill FullPath
Application.DisplayAlerts = True
MsgBox "COMPLETED CORRECTLY"
Exit Sub
XETA: MsgBox "THERE WAS A FAULT SOMEWHERE"
End Sub
Then you can use it like this:
Private Sub CommandButton1_Click()
Call XLSMtoXLSX(Date)
End Sub

Loop Freezing Excel After Printing

I have a spreadsheet that creates a CSV file and deposits the CSV file in a folder next to the original file. The spreadsheet seems to work fine. When you have your data entered, you click export, and a CSV file is put in a folder called "Uploads" that is next to the original file.
The issue is when I use the quick print button on my Excel quick access toolbar. When I click the quick print button, everything seems to print fine. However, as soon as I close the file, (EDIT: ALL Printing seems to be freezing the file. As soon as the file is closed) Excel then goes into a freeze where it looks like it is trying to run some code? I am a novice in VBA so I am not sure what is happening, all I know is that after my file is closed, Excel freezes up and I have to restart Excel. I do not even have any macros or VBA for an Excel close or Excel open trigger.
Can anyone recreate the issue and give me insight into how my code might be doing this?
Private Sub Export_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim MyPath As String
Dim MyFileName As String
'The path and file names:
MyPath = ActiveWorkbook.Path & "\Uploads"
MyFileName = "" & Range("a2") & "_Upload"
On Error GoTo Ending
'Makes sure the path name ends with "\":
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
'Makes sure the filename ends with ".csv"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
'Copies the sheet to a new workbook:
Sheets("UploadData").Copy
'The new workbook becomes Activeworkbook:
With ActiveWorkbook 'Saves the new workbook to given folder / filename:
.SaveAs FileName:= _
MyPath & MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False 'Closes the file
.Close False
End With
ChDir MyPath
Workbooks.Open FileName:= _
MyPath & "\" & MyFileName & """"
ActiveWorkbook.Save
ActiveWorkbook.Close
GoTo Skip
Ending:
MsgBox ("ERROR! Please make sure you have a folder named Uploads next to the template file")
ActiveWorkbook.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Skip:
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
This actually shouldn't work at all, regardless of what you do before you run it. First, you ensure that MyPath ends with a \ here...
'Makes sure the path name ends with "\":
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
...but then when you (re)build the same path below you're inserting a second \:
Workbooks.Open FileName:= _
MyPath & "\" & MyFileName & """"
This should always fail. You can avoid this entire problem with paths by using the Scripting.FileSystemObject's .BuildPath function:
'Requires a reference to Microsoft Scripting Runtime.
Dim filePath As String, fso As New Scripting.FileSystemObject
filePath = fso.BuildPath(ThisWorkbook.Path, MyFileName)
You can also use this for the file extension:
If LCase$(fso.GetExtensionName(MyFileName)) <> "csv" Then
MyFileName = MyFileName & ".csv"
End If
Note that this test will never be true...
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
...because MyFileName will always end with "load":
MyFileName = "" & Range("a2") & "_Upload"
Also, you should remove all the references to ActiveWorkbook. I have no idea why printing would effect this, but there isn't anything else I can identify that should be an issue. I'd structure it more like this (error handler removed for clarity - don't put it back until you're finished debugging it):
'Add a reference to Microsoft Scripting Runtime.
Private Sub Export_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
With New Scripting.FileSystemObject
Dim filePath As String
Dim targetDir As String
targetDir = .BuildPath(ThisWorkbook.Path, "Uploads")
If Not .FolderExists(targetDir) Then
MsgBox ("ERROR! Please make sure you have a folder named Uploads next to the template file")
Exit Sub
End If
filePath = .BuildPath(targetDir, ActiveSheet.Range("A2").Value & "_Upload.csv")
End With
'Copies the sheet to a new workbook:
Dim csv As Workbook
Set csv = Application.Workbooks.Add
With csv
ThisWorkbook.Sheets("UploadData").Copy .Sheets(1)
.SaveAs Filename:=filePath, _
FileFormat:=xlCSV, _
CreateBackup:=False 'Closes the file
.Close xlDoNotSaveChanges
End With
'Reopen and re-save to fix formatting.
Set csv = Workbooks.Open(filePath)
csv.Close xlSaveChanges
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Code to convert .xls to .xlsx

I found this code snippet online to convert my .xls files to .xlsx files.
Sub ProcessFiles()
Dim Filename, Pathname, SaveFileName As String
Dim wb As Workbook
Pathname = "C:\Users\user\Desktop\test\"
Filename = Dir(Pathname & "*.xls")
Application.DisplayAlerts = True
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
wb.CheckCompatibility = True
saveFileName = Replace(Filename, ".xls", ".xlsx")
wb.SaveAs Filename:=saveFileName
wb.Close SaveChanges:=True
Filename = Dir()
Loop
Application.DisplayAlerts = True
End Sub
When I run this it does create the back-up properly but when it comes to saving the file it displays the message that test.xls already exists in the folder, but I want it to be saved as .xlsx, as seen in the replace function.
What is wrong with the code?
Replace
wb.SaveAs Filename:=saveFileName
with
wb.SaveAs Filename:=saveFileName, FileFormat:=xlOpenXMLWorkbook
and replace
wb.Close SaveChanges:=True
with
wb.Close SaveChanges:=False

Resources