Worksheet save as .csv(Comma deli) and rename as .txt by cmd.exe

haribole

New Member
Joined
Apr 10, 2018
Messages
19
I am trying to save a sheet as .Csv (Comma delimited) and then rename as .Txt by Cmd.exe (Shell) but not working.
Please help me !!!

Dim MyFolder As String, MyFile As String, MySheetName as String
Dim ShellComand As String

.........

MyFolder = "D:\Revise"
MyFile = Dir(MyFolder & "\*.txt")
Workbooks.OpenText Filename:=MyFolder & "" & MyFile, StartRow:=1, DataType:=xlDelimited, Comma:=True, Tab:=False, Semicolon:=False, Space:=False, Other:=False, FieldInfo:=Array(Array(1, xlTextFormat), Array(2, xlTextFormat), Array(3, xlTextFormat))
MySheetName = Replace(ActiveWorkbook.Name, ".txt", "")
ActiveWorkbook.Sheets(1).Copy After:=Workbooks("Revise.xlsm").Worksheets(Sheets.Count)
ActiveSheet.Name = MySheetName
Worksheets(2).Activate
Application.DisplayAlerts = False
ActiveSheet.SaveAs Filename:=MyFolder & "" & MySheetName + "_Rev_" + Replace(Date, "-", ""), FileFormat:=xlCSV, CreateBackup:=True
'Problem here: .Csv file not saving with same cell format (text)
Application.DisplayAlerts = True
ShellComand = "cmd.exe /k ""cd " & """ & ThisWorkbook.path & """ & " ren *.csv *.txt"""
Shell ShellComand
'Problem here: it can't rename into .txt


Can anybody help me out of this problem ?
 

rlv01

Active Member
Joined
May 16, 2017
Messages
469
Instead of using notepad, why not save the file directly to a .txt extension?

Code:
Sub CSVFileSaveAsTxt()    ' save a .csv file with a .txt extention
    Dim MyFolder As String, MyFile As String, MySheetName As String
    Dim SaveAsFileName As String

    MyFolder = "D:\Revise"
    MyFile = Dir(MyFolder & "\*.txt")

    Workbooks.OpenText Filename:=MyFolder & "" & MyFile, StartRow:=1, DataType:=xlDelimited, Comma:=True, Tab:=False, Semicolon:=False, Space:=False, Other:=False, FieldInfo:=Array(Array(1, xlTextFormat), Array(2, xlTextFormat), Array(3, xlTextFormat))
    MySheetName = Replace(ActiveWorkbook.Name, ".txt", "")
    ActiveWorkbook.Sheets(1).Copy After:=Workbooks("Revise.xlsm").Worksheets(Sheets.Count)
    ActiveSheet.Name = MySheetName
    Worksheets(2).Activate
    Application.DisplayAlerts = False

    SaveAsFileName = MyFolder & "\" & MySheetName & "_Rev_" & Day(Date) & Month(Date) & Year(Date) & ".txt"
    ActiveSheet.Copy
    ActiveWorkbook.SaveAs Filename:=SaveAsFileName, FileFormat:=xlCSV, CreateBackup:=True
    ActiveWorkbook.Close False
    Application.DisplayAlerts = True
End Sub
BTW, for clarity when posting code
 

Forum statistics

Threads
1,086,235
Messages
5,388,624
Members
402,127
Latest member
Jemx

Some videos you may like

This Week's Hot Topics

Top