Save file as csv, keeps coming up as .xlsx - excel

I am trying to output a copy of a workbook as a CSV File. I have the code below but on saving it comes up in file type as Excel workbook.
Sub SAVE_CSV()
Dim FileName As String
FileName = "CSV Import File"
Dim fPth As Object
Set fPth = Application.FileDialog(msoFileDialogSaveAs)
With fPth
.InitialFileName = FileName
.Title = "Save Your Import File"
.InitialView = msoFileDialogViewList
If .Show <> 0 Then
ThisWorkbook.SaveAs FileName:=.SelectedItems(1) & "*.csv", FileFormat:=xlCSV
End If
End With

You know the name you want to save it as, so maybe it's just a case of selecting the right folder:
Sub SAVE_CSV()
Dim FileName As String
FileName = "CSV Import File Again"
Dim fPth As Object
Set fPth = Application.FileDialog(msoFileDialogFolderPicker)
With fPth
.InitialFileName = "C:\Users\Testing\Documents\Can be deleted\" 'Change as required.
.Title = "Save Your Import File"
.InitialView = msoFileDialogViewList
If .Show <> 0 Then
ThisWorkbook.SaveAs FileName:=.SelectedItems(1) & "\" & FileName & ".csv", FileFormat:=xlCSV
End If
End With
End Sub

Replace with:
ThisWorkbook.SaveAs FileName:=.SelectedItems(1) & ".csv"
Follow the below logic:
Path - Directory
"\"
File Name
File type - .csv

Related

GetOpenFilename Default Location to Downloads

I don't see any parameter in GetOpenFilename to set default folder to Downloads.
Currently, it opens Documents folder. Is it possible to make the default location as Downloads folder.
I can't hardcode the path as Downloads without including the Username.
e.g C:\Users\NameOfUser\Downloads
**********Solution**********
Dim FilePaths As FileDialogSelectedItems
Dim iFolderPath As String
iFolderPath = Environ("USERPROFILE") _
& Application.PathSeparator & "Downloads" & Application.PathSeparator
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = True
.Filters.Clear
.Filters.Add "Open CSV", "*.csv"
.InitialFileName = iFolderPath
If .Show <> -1 Then
Do
ans = MsgBox("No file selected. Cannot continue.", 53, "Try again")
If ans = 2 Then Exit Do
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = True
.Filters.Clear
.Filters.Add "Open CSV", "*.csv"
.InitialFileName = iFolderPath
.Show
End With
Loop
If ans = 2 Then MsgBox "No file selected. User cancelled.", vbInformation, "Special"
Exit Sub
End If
Set FilePaths = .SelectedItems
End With
Dim FilePath As Variant
For Each FilePath In FilePaths
Workbooks.Open FilePath
Next FilePath
Choose Files to Open (FileDialog)
Here is a different way that uses the FileDialog object.
Use the Environ function to build the initial path.
Sub ChooseFilesToOpen()
Dim iFolderPath As String: iFolderPath = Environ("USERPROFILE") _
& Application.PathSeparator & "Downloads" & Application.PathSeparator
Dim FilePaths As FileDialogSelectedItems
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = True
.Filters.Clear
.Filters.Add "Excel Workbook", "*.xlsx"
.InitialFileName = iFolderPath
If .Show <> -1 Then
MsgBox "Canceled.", vbExclamation
Exit Sub
End If
Set FilePaths = .SelectedItems
End With
Dim FilePath As Variant
For Each FilePath In FilePaths
Debug.Print FilePath
Next FilePath
End Sub

Converting multiple xlsl files to xls (97-2003 Worksheet) extension without changing the names

I am trying to loop through all the 'xlsx' files in a folder and convert them to 'xls' ( Excel 97-2003 Worksheet) format. I use the following codes but then the output files are still saved as 'xlsx' instead of 'xls'. I am a beginner and looking to learn more from others. Thanks for your help!
Sub Convert()
Dim strPath As String
Dim strFile As String
Dim strfilenew As String
Dim xWbk As Workbook
Dim xSFD, xRFD As FileDialog
Dim xSPath As String
Dim xRPath As String
Set xSFD = Application.FileDialog(msoFileDialogFolderPicker)
With xSFD
.Title = "Please select the folder contains the xls files:"
.InitialFileName = "C:\"
End With
If xSFD.Show <> -1 Then Exit Sub
xSPath = xSFD.SelectedItems.Item(1)
Set xRFD = Application.FileDialog(msoFileDialogFolderPicker)
With xRFD
.Title = "Please select a folder for outputting the new files:"
.InitialFileName = "C:\"
End With
If xRFD.Show <> -1 Then Exit Sub
xRPath = xRFD.SelectedItems.Item(1) & "\"
strPath = xSPath & "\"
strFile = Dir(strPath & "*.xlsx")
strfilenew = Dir(strPath & "*.xls")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While strFile <> ""
If Right(strFile, 4) = "xlsx" Then
Set xWbk = Workbooks.Open(Filename:=strPath & strfilenew)
xWbk.SaveAs Filename:=xRPath & strfilenew, _
FileFormat:=xlExcel18
xWbk.Close SaveChanges:=True
End If
strFile = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
There was a bit of a mix-up in your file naming, basically as evidenced by the several double-declarations that I removed. The really big mistake was here, Set xWbk = Workbooks.Open(Filename:=strPath & strfilenew) where you tried to open the old workbook by the new name. I think the confusion started here "Please select the folder contains the xls files:". Of course, this is the folder with the XLSX files. The recommended antidote is to use "meaningful" variable names but you chose to speak in riddles (like xSFD) which makes coding more difficult.
However, the code below is largely yours, and it does work.
Sub Convert()
' 230
Dim Spath As String ' path to read from (XLSX files)
Dim Rpath As String ' path to write to (XLS files)
Dim strFile As String ' loop variable: current file name
Dim Wbk As Workbook ' loop object: current workbook(strFile)
Dim Sp() As String ' split array of strFile
Dim strFileNew As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select the folder contains the XLSX files:"
.InitialFileName = "C:\"
If .Show <> -1 Then Exit Sub
Spath = .SelectedItems.Item(1) & "\"
End With
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder for outputting the new files:"
.InitialFileName = "C:\"
If .Show <> -1 Then Exit Sub
Rpath = .SelectedItems.Item(1) & "\"
End With
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
strFile = Dir(Spath & "*.xlsx")
Do While strFile <> ""
If Right(strFile, 4) = "xlsx" Then
Sp = Split(strFile, ".")
Sp(UBound(Sp)) = "xls"
strFileNew = Join(Sp, ".")
Set Wbk = Workbooks.Open(Filename:=Spath & strFile)
Wbk.SaveAs Filename:=Rpath & strFileNew, FileFormat:=xlExcel8
Wbk.Close SaveChanges:=True
End If
strFile = Dir
Loop
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub
Observe that the new file name is created by splitting the old name on periods, changing the last element, and reassembling the modified array.

Bad file name or number vba

my code keeps getting a bad file name or number error and I can't figure out what the issue is, any help would be appreciated! I'm trying to store the filepath based on user selection as a variable which I can reference later in a vlookup. Below is my code, I can't figure out what's wrong but I used the pasted code in another macro which compiled fine.
sub edits
dim xpath and xfile as string
xPath = NewPath 'Newpath function executes
xfile = Dir$(xPath & "*.xlsm*", vbNormal) 'error here
Set SourceBook = Workbooks.Open(xPath & xfile)
End Sub
Function NewPath() As String
With Application.FileDialog(msoFileDialogOpen)
.ButtonName = "Choose a file"
.Title = "Previous File"
.AllowMultiSelect = False
If .Show Then xPath = .SelectedItems(1) & "\"
End With
End Function
Below is the code I've used which has compiled, it has the user select a folder instead of a file
sub something
dim xpath and xfile as string
xPath = NewPath
If Not strPath = vbNullString Then
xfile = Dir$(xPath & "*.xlsm", vbNormal)
Do While Not xfile = vbNullString
'some code
Set SourceBook = Workbooks.Open(xPath & xfile)
SourceBook.Close False
xfile = Dir$()
Loop
End If
End Sub
Function NewPath() As String
With Application.FileDialog(msoFileDialogFolderPicker)
.ButtonName = "Choose a folder"
.Title = "Folder Picker"
.AllowMultiSelect = False
If .Show Then NewPath = .SelectedItems(1) & "\"
End With
End Function

VBA Code to Save As .XLSM

Need assistance to add command to save as .xlsm :-
Private Sub cmdSaveForm1_Click()
Dim strFolder As String
Dim i As Long
'Find the position of the period in the file name
i = InStr(ActiveWorkbook.Name, ".")
'Create a default file name by concatenating the file name without the extention _
plus the current date and time, and plus the xlsm extention
Filename = Left(ActiveWorkbook.Name, i - 1) & "_" & Format(Now, "yyyy-mm-dd_hh mm") & ".xlsm"
'Open Save As dialog to a default folder with default file name
With Application.FileDialog(msoFileDialogSaveAs)
.AllowMultiSelect = False
.InitialFileName = "P:\EU Funds Management - Treasury\TRS3_Abstract of Payments\TRS3_Authorisation_L1\" & Filename
.InitialView = msoFileDialogViewDetails
If .Show = -1 Then strFolder = .SelectedItems(1) Else Exit Sub
.Execute
End With
End Sub
To save a Workbook as .xlsm you need the following file format
Excel 2007-2010 Macro-Enabled Workbook (.xlsm) - 52 - xlOpenXMLWorkbookMacroEnabled
To save a file to an chosen format you need to specify the appropriate format when saving. This can be done by adding FileFormat:= to your save action.
ThisWorkbook.SaveAs Filename:=Path & Filename, FileFormat:=xlOpenXMLWorkbookMacroEnabled
Below the addition of the save action and FileFormat to your code.
Private Sub cmdSaveForm1_Click()
Dim strFolder As String
Dim i As Long
'Find the position of the period in the file name
i = InStr(ActiveWorkbook.Name, ".")
'Create a default file name by concatenating the file name without the extention _
plus the current date and time, and plus the xlsm extention
Filename = Left(ActiveWorkbook.Name, i - 1) & "_" & Format(Now, "yyyy-mm-dd_hh mm") & ".xlsm"
'Open Save As dialog to a default folder with default file name
With Application.FileDialog(msoFileDialogSaveAs)
.AllowMultiSelect = False
.InitialFileName = "P:\EU Funds Management - Treasury\TRS3_Abstract of Payments\TRS3_Authorisation_L1\" & Filename
.InitialView = msoFileDialogViewDetails
If .Show = -1 Then strFolder = .SelectedItems(1) Else Exit Sub
'get selected folder path from FileDialog, but remove filename from FileDialog
folderPath = Left(strFolder, InStrRev(strFolder, "\"))
'Save this workbook in chosen file path & appropriate filename
'File format .xlsm
ThisWorkbook.SaveAs Filename:=folderPath & Filename, FileFormat:=xlOpenXMLWorkbookMacroEnabled
End With
End Sub
Different Fileformats for excel are:
.xlsx = 51 '(52 for Mac)
.xlsm = 52 '(53 for Mac)
.xlsb = 50 '(51 for Mac)
.xls = 56 '(57 for Mac)
ActiveWorkbook.SaveAs FileFormat:=52 '=.xlsm in Windows
The solution is:
.FilterIndex = 2
1 = xlsx, 2 = xlsm
Private Sub cmdSaveForm1_Click()
Dim strFolder As String
Dim i As Long
'Find the position of the period in the file name
i = InStr(ActiveWorkbook.Name, ".")
'Create a default file name by concatenating the file name without the extention _
plus the current date and time, and plus the xlsm extention
Filename = Left(ActiveWorkbook.Name, i - 1) & "_" & Format(Now, "yyyy-mm-dd_hh mm") & ".xlsm"
'Open Save As dialog to a default folder with default file name
With Application.FileDialog(msoFileDialogSaveAs)
.AllowMultiSelect = False
.FilterIndex = 2 '2 = xlsm
.InitialFileName = "P:\EU Funds Management - Treasury\TRS3_Abstract of Payments\TRS3_Authorisation_L1\" & Filename
.InitialView = msoFileDialogViewDetails
If .Show = -1 Then strFolder = .SelectedItems(1) Else Exit Sub
.Execute
End With
End Sub

String obtained from FileDialog does not display in message box

I'm trying to display where a file is saved in a message box with the following code:
Sub export()
Dim MyPath As String
Dim MyFileName As String
MyFileName = "MyFileName"
Worksheets("Tab").Copy
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = "Path"
If .Show = -1 Then
GoTo Nextcode1
Else
GoTo Nextcode2
End If
MyPath = .SelectedItems(1) & "\"
End With
Nextcode1:
Block of codes that deals with existing file name.
GoTo Nextcode3
Nextcode2:
Block of codes that deals with cancel.
GoTo Nextcode4
NextCode3:
Application.DisplayAlerts = False
With ActiveWorkbook
.SaveAs fileName:=MyPath & MyFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close False
End With
Application.DisplayAlerts = True
Worksheets("OtherTab").Activate
MsgBox ("The tab has been exported to " & MyPath & MyFileName & ".")
GoTo NextCode4
NextCode4:
End Sub
However, the message box only displays
The tab has been exported to MyFileName.
With MyPath completely omitted. I tried the following codes
PathName = MyPath & MyFileName
MsgBox ("The tab has been exported to " & PathName & ".")
And
Cstr(MyPath)
MsgBox ("The tab has been exported to " & MyPath & MyFileName & ".")
To no avail. My suspicion is that path name obtained from the msoFileDialogFolderPicker is not a string object but I'm not sure how to deal with it. Help is appreciated!
Ok my bad. The
MyPath = .SelectedItems(1) & "\"
line should have gone under
If .Show = -1 Then

Resources