How to change file extensions in VBA - vba

I feel like this must be simple, but I can't find the answer. I'm saving a bunch of csv files using vba and would like to change all the file extensions from .csv to .txt to import into another program (Revit) which only recognizes the .txt extension. Is this possible? Here is the command I'm using.
For I = 1 To WS_Count
path = CurDir() + "\" + ActiveWorkbook.Worksheets(I).Name
Sheets(ActiveWorkbook.Worksheets(I).Name).Select
ActiveWorkbook.SaveAs Filename:=path, FileFormat:=xlCSV, CreateBackup:=False
Name path As ("path" + ".txt")
Next I
Thanks!

You don't even need to open the files to rename them.
Sub M_snb()
name "G:\OF\example.csv" As "G:\OF\example.txt"
end sub

You should change
FileFormat:=xlCSV
to
FileFormat:=xlTextWindows
See
https://msdn.microsoft.com/en-us/library/office/ff198017.aspx
or
The xlFileFormat enumeration (Excel) on MSDN

Ok got it. You can just ad txt to the file name, even if it is in the CSV format.
WS_Count = ActiveWorkbook.Worksheets.Count
For I = 1 To WS_Count
path = CurDir() + "\" + ActiveWorkbook.Worksheets(I).Name + ".txt"
Sheets(ActiveWorkbook.Worksheets(I).Name).Select
ActiveWorkbook.SaveAs Filename:=path, FileFormat:=xlCSV, CreateBackup:=False
Debug.Print (test)
Debug.Print (path)
Next I

Try this. It will get the file from the specified directory from your system and will return the converted file from CSV to Text.
Sub changeExt()
strDir = "C:\Users\user\Desktop\xyz" 'Your file directory
With CreateObject("wscript.shell")
.currentdirectory = strDir
.Run "%comspec% /c ren *.csv *.txt", 0, True
End With
End Sub

Related

VBA pick a file from a specific location?

I'm attempting to put together some code in VBA where it will open a specific folder, let me choose the file then continue running my code.
Currently what I have (below) "works" in that it will open a folder but usually it starts from a generic location (Desktop) but will not go the the specific folder location to let me open the file I want.
Dim Filename as String
filename = Application.GetOpenFilename(FileFilter:="Excel Files, *.xl*;*.xm*")
If filename <> False Then
Workbooks.Open filename:=filename
End If
I've also tried something like this:
Dim Directory as String
Dim Filename as String
Directory = "\\page\data\NFInventory\groups\CID\Retail Setting\Lago Retail Uploads\" & strBrand & "\" & strSeason & "\" & strPrefix & "\"
Filename = Dir(Directory & "*.xl*;*.xm*")
Workbooks.Open Filename:=Directory
But it doesn't do anything and I think I have everything right. Any help or push in the right direction would be greatly appreciated.
-Deke
This will start an Open Dialog at the specified location:
Sub openBeckJFolder()
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = True
.Show
.InitialFileName = "C:\Users\beckj\"
End With
End Sub
The Microsoft document page doesn't really get into it, but FileDialog has several features such as the InitialFileName that I used here.
_
UPDATE: To open the workbook
Code added that allows you to highlight the workbook & click Open, or double-click on the workbook to open it.
Sub openBeckJFolder()
Dim Filename As String
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.InitialFileName = "C:\Users\beckj\"
If .Show = True Then
Filename = .SelectedItems(1)
End If
End With
Workbooks.Open (Filename)
End Sub

Copying selected Excel File using macro to the different location along with its content

I am working on macro and I want to write a VBA code to select a file from a particular directory and create a Exact copy of that file with the new name to a particular location.
This is my code to browse and select a file and I want to create a Excel file with same content (including sheets and data present inside those sheets) to a new directory.
Sub BrowseForJ3File()
j3ExcelSheet = Application.GetOpenFilename(FileFilter:="Excel Workbooks (*.xls*),*.xls*", Title:="Open Excel File")
If fileToOpen <> False Then
MsgBox "Open " & fileToOpen
End If
ActiveSheet.Range("H9") = j3ExcelSheet
End Sub
I want to create exact copy of j3ExcelSheet but with a new name and with the same contents present in j3ExcelSheet to a particular location.
Use FileCopy
FileCopy j3ExcelSheet, "C:\Users\IamWhoIam\GloriousSubfolder\Test.xls"
How about something like below, this will open the file and Save As whatever filename you want, the other answers will copy the files, the difference with this option, is that you can also manipulate the data in the workbook (if you want to before saving it):
Sub BrowseForJ3File()
Dim x As Workbook
j3ExcelSheet = Application.GetOpenFilename(FileFilter:="Excel Workbooks (*.xls*),*.xls*", Title:="Open Excel File")
ActiveSheet.Range("H9") = j3ExcelSheet
Pos = InStrRev(j3ExcelSheet, "\")
Filename = Mid(j3ExcelSheet, Pos + 1)
'above get the filename
Pos = InStrRev(Filename, ".")
Extension = Mid(Filename, Pos + 1)
'above get the extension
Savepath = "C:\Users\Me\Desktop\"
'get the path to save the new file
NewFilename = "New Report"
'above new filename
Application.DisplayAlerts = False
Set x = Workbooks.Open(j3ExcelSheet)
With x
.SaveAs Savepath & Format(Date, "yyyymm") & " " & NewFilename & "." & Extension
.Close
End With
Application.DisplayAlerts = True
End Sub

VBA Excel file to CSV, keeps CSV filename same as original workbook

I am trying to find a fast way to save my xlsx files as csv files with the same file-name as the xlsx file (just in csv format). I have recorded a macro with shortcut, But the issue is that whenever I try with a new file it saves as a the same file-name I recorded initial macro with (i.e. see below, probably because I have the file labelled in code as: 3WDL_1 (2014-08-07)10secDataTable sit.csv). Is there something I need to replace 3WDL_1 (2014-08-07)10secDataTable sit.csv with to make the macro save with the same file-name as the actual workbook I am working with.
So basically I have a folder full of xlsx files and I want to use a shortcut/macro on each xslx file to convert them into a csv files that have exactly the same name as original xlsx file, and are saved into the same folder.
Sub xlstocsv()
'
' xlstocsv Macro
'
' Keyboard Shortcut: Ctrl+a
'
Columns("A:A").Select
Range("A41243").Activate
Selection.NumberFormat = "0.00"
ActiveWindow.ScrollRow = 41231
ActiveWindow.ScrollRow = 41090
ActiveWindow.ScrollRow = 39753
ActiveWindow.ScrollRow = 30184
ActiveWindow.ScrollRow = 26385
ActiveWindow.ScrollRow = 13017
ActiveWindow.ScrollRow = 10976
ActiveWindow.ScrollRow = 8162
ActiveWindow.ScrollRow = 4785
ActiveWindow.ScrollRow = 4503
ActiveWindow.ScrollRow = 774
ActiveWindow.ScrollRow = 1
Range("A1").Select
ChDir "C:\Users\paddy\Desktop\NEW CSV files whole CGM date ok!"
ActiveWorkbook.SaveAs Filename:= _
"C:\Users\paddy\Desktop\NEW CSV files whole CGM date ok!\3WDL_1 (2014-08-07)10secDataTable sit.csv" _
, FileFormat:=xlCSVMac, CreateBackup:=False
End Sub
Right now, you've got the file-name hard-coded in after "ActiveWorkbook.SaveAs" so it's saving everything with that hard-coded name.
I think you'll want to use "ActiveWorkbook.Name" to get the name of the current file and concatenate it into the "Filename" variable that you have there (without the file extension) with the new extension. For example:
"C:\Users\padd\Desktop\NEW CSV...ok!\" & Left(ActiveWorkbook.Name, InStr(ActiveWorkbook.Name, ".") - 1) & ".csv")
This is a kind of a dirty way to do it, but it should serve your needs. Also, depending on which version of Excel you use, I think you might need to use "ThisWorkbook" instead of "ActiveWorkbook" but I'm not sure.
Before saving as csv, get the name of the xls file. You can use the ActiveWorkbook.Nameproperty. Assuming that file is called something.xls(and not .xlsx), try this:
Sub Macro1()
XLSName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)
ActiveWorkbook.SaveAs Filename:="C:\Users\Username\Desktop\" & XLSName & ".csv", _
FileFormat:=xlCSV, CreateBackup:=False
End Sub
This pulls the workbook name, cuts off the last 4 characters (".xls") and then runs the Save As command appending ".csv" to that. In case your Excel file has the xlsx extension, change line 2 to:
XLSName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5)
Let me know if this works for you.
I would organize the pieces before stitching them together with standard string concatenation. Here is the relevant section of the code using the InStr function.
Dim myPath As String, myFileName As String
myPath = "C:\Users\paddy\Desktop\NEW CSV files whole CGM date ok!"
'possible alternate that gets the environment variable USERNAME
'myPath = "C:\Users\" & Environ("USERNAME") & "\Desktop\NEW CSV files whole CGM date ok!"
'check if the folder exists and if not create it
If Not CBool(Len(Dir(myPath, vbDirectory))) Then _
MkDir Path:=myPath
myFileName = Left(ActiveWorkbook.Name, InStr(1, ActiveWorkbook.Name, ".xl", vbTextCompare) - 1)
'you don't actually need .csv as the extension if you are explicitly saving as xlCSV or xlCSVMac but here is an alternate
'myFileName = Left(ActiveWorkbook.Name, InStr(1, ActiveWorkbook.Name, ".xl", vbTextCompare) - 1) & ".csv"
'output to the VBE's Immediate window for checking later in case there is a problem
Debug.Print myPath & Chr(92) & myFileName
' the backslash is ASCII character 92
ActiveWorkbook.SaveAs Filename:=myPath & Chr(92) & myFileName, _
FileFormat:=xlCSVMac, CreateBackup:=False
I'm not sure what all the scrolling was doing; it probably isn't necessary. You might want to add in the number formatting command.

How to open file with format date and time in excel vba

I want to open and copy sheet in file TFM_20150224_084502 and this file has different date and time each day. I have developed code until open the date format but I can't develop to open it with time format.
What's the more code for it?
Sub OpenCopy ()
Dim directory As String, fileName As String, sheet As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
directory = "z:\FY1415\FI\Weekly Report\Astry"
fileName = "TFM_" & Format(Date, "yyyymmdd") & ".xls"
Workbooks.Open "z:\FY1415\FI\Weekly Report\Astry\" & "TFM_" & Format(Date, "yyyymmdd") & ".xls"
Sheets("MSP").Copy After:=Workbooks("Generate Report 2.xlsm").Sheets("PlanOEE")
ActiveSheet.Name = "MSP"
End sub
It seems that some linebreaks have disappeared when you posted the code into your post, but assuming you are aware of this, I assume that the main problem you have is figuring out the name of the file you want to open?
The VBA Dir-function lets you search for a file in a folder, and lets you include wildcards in your search. I've included this function in your sub, and have tested it with a similarly named file on my computer (albeit without the copying of the sheet), and it opened the sheet:
Sub OpenCopy()
Dim directory As String, fileName As String, sheet As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
directory = "z:\FY1415\FI\Weekly Report\Astry\"
fileName = Dir(directory & "TFM_" & Format(Date, "yyyymmdd") & "*.xls*")
If fileName <> "" Then
With Workbooks.Open(directory & fileName)
.Sheets("MSP").Copy After:=Workbooks("Generate Report 2.xlsm").Sheets("PlanOEE")
End With
ActiveSheet.Name = "MSP"
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
The line relevant for finding the filename is, as you probably see:
fileName = Dir(directory & "TFM_" & Format(Date, "yyyymmdd") & "*.xls*")
I have simply used Dir to do a search for file fitting the string inside the parantheses, where the asterisks are wildcards. The reason I have included an asterisk after xls too is because there is a chance the file can have extensions such as xlsx or xlsm in newer versions of office. I've also added a backslash at the end of the directory string, since you'll have to include it before the filename anyway.
I have also added an if-clause around what you do with the workbook you open, in case no file fitting the search is found.
Note that this sub will only do what you want provided that there only is one file generated for each date. If you want to loop through all files which includes a given date, I would recommend having a look at this post here on SO, which explains how to loop through all files in a folder, modifying the macros presented there to fit your needs should be fairly trivial.

how to convert .docx and .pdf to .txt file

I am working on an application for which i need to convert .docx and .pdf file to .txt
file with basic formatting. I searched it in internet but couldn't find any free third party dlls. Can any one suggest me best way and some dlls reference for this.
Thanks in Advance
http://support.microsoft.com/kb/316383 describes what you want to do with .docx files very well.
http://visualbasic.about.com/od/quicktips/qt/disppdf.htm describes the same, but with .pdf files.
Once you have read files into your code, output to a txt file using VB.NET's built in file writing functions.
The code below will handle the job for you. It is something I wrote for the big boss haha. I hope it helps. The code reads the first cell in the work sheet as the folder where docx files are present and then converts them to txt files one by one saving in the same folder.
Const wdFormatText = 2
If Not Len(Cells(1, "A").Value) > 0 Or Dir(Cells(1, "A").Value, vbDirectory) = "" Then
MsgBox ("Invalid Folder")
Exit Sub
End If
Dim StrFile As String
StrFile = Dir(Cells(1, "A").Value & "\*.docx")
Do While Len(StrFile) > 0
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(Cells(1, "A").Value & "\" & StrFile, False, True)
objDoc.SaveAs Cells(1, "A").Value & "\" & StrFile & ".txt", wdFormatText
objWord.Quit
StrFile = Dir
Loop