Tab delimited text file to Excel file with text formatted - excel

I am new to VB Programming .I want to convert a text file into a excel file.The text file is comma seperated and Unicode file.And the converted excel file should have all fields in text format(To preserve the prefixed Zeros).After converting the text file to excel with the below code,the zeros are truncated in the excel file.First i am converting the text file with comma delimited to tab delimited and loading the tab delimited text file into excel.
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("SOURCE_FILE_PATH.txt", ForReading,False,-1)
strContents = objFile.ReadAll
objFile.Close
strContents = Replace(strContents, ",", vbTab)
Set objFile = objFSO.OpenTextFile("SOURCE_FILE_PATH.txt", ForWriting, True, -1)
objFile.Write strContents
objFile.Close
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open(Wscript.Arguments.Item(0))
objWorkbook.Saveas WScript.Arguments.Item(1),51
objWorkbook.Close False
Set objWorkbook = objExcel.Workbooks.Open("Target_XLSX_FILE_PATH.xlsx")
objExcel.Visible = True
Set objRange = objExcel.Range("A:K")
objRange.NumberFormat = "#"--converting to text format
objExcel.Save
objWorkbook.Close False
objexcel.Quit
In the line
Set objWorkbook = objExcel.Workbooks.Open(Wscript.Arguments.Item(0))
The tab delimited file is loaded in to various columns with Genetal format.After i convert that to text format also,The zeros won't be there.
Thanks in advance for the help.

There's no need to actually use FSO for this, if you're not going to do anything to the data inside the text file prior to importing to Excel.
This is my data:
This is the code:
Sub TextOpen()
arrtext = Array(Array(1, 2), Array(2, 2), Array(3, 2), Array(4, 2))
Workbooks.OpenText Filename:="C:\Users\jeromem\Desktop\BK201.txt", Comma:=True, FieldInfo:=arrtext
End Sub
This is the result after running:
Check this for the OpenText method and this for the FieldInfo data types. As you can see there, text format is equal to 2.
arrtext is basically read as, for column 1 of text, apply format 2; for column 2 of text, apply format 2..... We then feed this array to FieldInfo. We also set Comma:=True since this is the delimiter in your text file.
Let us know if this helps.

Related

How to maintain character set while exporting Excel table to .csv UTF8 without BOM using VBA?

I have read several other answers regarding how to export a table to .csv with UTF8 encoding (no BOM). I found code which almost works for me, see below.
My problem is that the table contains swedish characters (ÅÄÖ), and when the .csv-file is opened these are lost to what looks like an incorrect charset. I found a workaround which is to open the .csv-file in Notepad, save, and then open it in Excel. The workaround makes Excel display the letters properly, but I would prefer not to have the extra step. Can the code below be modified so that the charset is not lost?
Option Explicit
Sub CSVFileAsUTF8WithoutBOM()
Dim SrcRange As Range
Dim CurrRow As Range
Dim CurrCell As Range
Dim CurrTextStr As String
Dim ListSep As String
Dim FName As Variant
Dim UTFStream As Object
Dim BinaryStream As Object
' ADO Constants
Const adTypeBinary = 1 ' The stream contains binary data
Const adTypeText = 2 ' The stream contains text data (default)
Const adWriteLine = 1 ' write text string and a line separator (as defined by the LineSeparator property) to the stream.
Const adModeReadWrite = 3 ' Read/write
Const adLF = 10 ' Line feed only - default is carriage return line feed (adCRLF)
Const adSaveCreateOverWrite = 2 ' Overwrites the file with the data from the currently open Stream object, if the file already exists
' Open this workbook location
ChDrive Left(ThisWorkbook.Path, 1)
ChDir ThisWorkbook.Path
' ask for file name and path
FName = Application.GetSaveAsFilename("", "CSV File (*.csv), *.csv")
' prepare UTF-8 stream
Set UTFStream = CreateObject("adodb.stream")
UTFStream.Type = adTypeText
UTFStream.Mode = adModeReadWrite
UTFStream.Charset = "UTF-8"
UTFStream.LineSeparator = adLF
UTFStream.Open
'set field separator
ListSep = ";"
'set source range with data for csv file
If Selection.Cells.Count > 1 Then
Set SrcRange = Selection
Else
Set SrcRange = ActiveSheet.UsedRange
End If
For Each CurrRow In SrcRange.Rows
CurrTextStr = ""
For Each CurrCell In CurrRow.Cells
CurrTextStr = CurrTextStr & Replace(CurrCell.Value, """", """""") & ListSep
Next
'remove ListSep after the last value in line
While Right(CurrTextStr, 1) = ListSep
CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1)
Wend
'add line to UTFStream
UTFStream.WriteText CurrTextStr, adWriteLine ' Writes character data to a text Stream object
Next
'skip BOM
UTFStream.Position = 3 ' sets or returns a long value that indicates the current position (in bytes) from the beginning of a Stream object
'copy UTFStream to BinaryStream
Set BinaryStream = CreateObject("adodb.stream")
BinaryStream.Type = adTypeBinary
BinaryStream.Mode = adModeReadWrite
BinaryStream.Open ' Opens a Stream object
'Strips BOM (first 3 bytes)
UTFStream.CopyTo BinaryStream ' Copies a specified number of characters/bytes from one Stream object into another Stream object
UTFStream.Flush ' Sends the contents of the Stream buffer to the associated underlying object
UTFStream.Close ' Closes a Stream object
'save to file
BinaryStream.SaveToFile FName, adSaveCreateOverWrite
BinaryStream.Flush ' Sends the contents of the Stream buffer to the associated underlying object
BinaryStream.Close ' Closes a Stream object
End Sub
EDIT:
Based on your comment, I realize that what you initially wanted was to keep the information about the character encoding inside the file without having a BOM.
The problem with this question (as you realized it) is that the BOM is actually what normally contains the information about the character encoding and putting this information anywhere else in the file doesn't really make sense.
So, your code is actually perfect for the task at hand. What needs to be changed is how the CSV file is imported/opened by the software you want to use.
When the file has no BOM, a software reading the file has to guess the
character encoding.
In general, if the software you use doesn't support BOM and doesn't guess correctly, there should at least be a way to customize the behavior of the import/open command so that you can specify the character encoding (seems like you actually found it).
Original answer:
For some reason, Excel has a hard time to guess the character encoding when opening a UTF-8 encoded CSV file when you just double-clicking the file. You have to help it a little...
Instead of opening it directly, you could load the CSV content to a new workbook by using the (legacy) Text Import Wizard and selecting the UTF-8 character set (65001) during import if Excel is not able to figure it out by itself.
If you were to record a macro while doing it and make it into a sub procedure, you could have something like this:
Sub OpenCSV(FullFileName As String)
Dim wb As Workbook
Set wb = Workbooks.Add
Dim ws As Worksheet
Set ws = wb.Sheets(1)
With ws.QueryTables.Add(Connection:= _
"TEXT;" & FullFileName, Destination:=Range( _
"$A$1"))
.Name = "CSV_Open"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 65001
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Other suggestion
If you really want to be able to double-click the file instead of using the Text Import Wizard or running a macro, you could always create a VBA event procedure in an add-in or PERSONAL.XSLB running every time a workbook is opened.
If it detects that the file that was just opened is a CSV file, it could close it and "reopen" it using the code above.
Extra:
Of interest: there is a question here about how to change the default character encoding that Excel uses.

VBScript Importing .txt file to .xlsx file [duplicate]

I'm trying to convert pipe-delimited files to xls (Excel) with batch file and vbscript. Unfortunately, my "output.xls" file is still showing the pipe delimiter in the table and the data are not organized.
srccsvfile = Wscript.Arguments(0)
tgtxlsfile = Wscript.Arguments(1)
'Create Spreadsheet
'Look for an existing Excel instance.
On Error Resume Next ' Turn on the error handling flag
Set objExcel = GetObject(,"Excel.Application")
'If not found, create a new instance.
If Err.Number = 429 Then '> 0
Set objExcel = CreateObject("Excel.Application")
End If
objExcel.Visible = false
objExcel.displayalerts=false
'Import CSV into Spreadsheet
Set objWorkbook = objExcel.Workbooks.open(srccsvfile)
Set objWorksheet1 = objWorkbook.Worksheets(1)
'Adjust width of columns
Set objRange = objWorksheet1.UsedRange
objRange.EntireColumn.Autofit()
'This code could be used to AutoFit a select number of columns
'For intColumns = 1 To 17
' objExcel.Columns(intColumns).AutoFit()
'Next
'Make Headings Bold
objExcel.Rows(1).Font.Bold = TRUE
'Freeze header row
With objExcel.ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
objExcel.ActiveWindow.FreezePanes = True
'Add Data Filters to Heading Row
objExcel.Rows(1).AutoFilter
'set header row gray
objExcel.Rows(1).Interior.ColorIndex = 15
'-0.249977111117893
'Save Spreadsheet, 51 = Excel 2007-2010
objWorksheet1.SaveAs tgtxlsfile, 51
'Release Lock on Spreadsheet
objExcel.Quit()
Set objWorksheet1 = Nothing
Set objWorkbook = Nothing
Set ObjExcel = Nothing
source :http://www.tek-tips.com/viewthread.cfm?qid=1682555
Pipe doesn't equal Comma, Excel natively knows what to do with a CSV, but not with Pipe.
All is not lost, record your actions opening the file manually, once open highlight column A and click Data / Text To Columns, choose delimited and in the "other" box put a pipe then click next, choose the column formats (great to format numbers as text if you need to like Postcodes and phone numbers) then click finish.
Now stop the recorder and look at the code it generated. Port this over to your Excel object in your script.
Excel is a little picky when it comes to reading CSV files. If you have a delimited file with the extension .csv Excel will only open it correctly via the Open method if the delimiter is the character configured in the system's regional settings.
The Open method has optional parameters that allow you to specify a custom delimiter character (credit to #Jeeped for pointing this out):
set objWorkbook = objExcel.Workbooks.Open(srccsvfile, , , 6, , , , , "|")
You can also use the OpenText method (which will be used when recording the action as a macro):
objExcel.Workbooks.OpenText srccsvfile, , , 1, , , , , , , True, "|"
Set objWorkbook = objExcel.Workbooks(1)
Note that the OpenText method does not return a workbook object, so you must assign the workbook to a variable yourself after opening the file.
Important: either way your file must not have the extension .csv if your delimiter character differs from your system's regional settings, otherwise the delimiter will be ignored.

Convert pipe-delimited files to .xls

I'm trying to convert pipe-delimited files to xls (Excel) with batch file and vbscript. Unfortunately, my "output.xls" file is still showing the pipe delimiter in the table and the data are not organized.
srccsvfile = Wscript.Arguments(0)
tgtxlsfile = Wscript.Arguments(1)
'Create Spreadsheet
'Look for an existing Excel instance.
On Error Resume Next ' Turn on the error handling flag
Set objExcel = GetObject(,"Excel.Application")
'If not found, create a new instance.
If Err.Number = 429 Then '> 0
Set objExcel = CreateObject("Excel.Application")
End If
objExcel.Visible = false
objExcel.displayalerts=false
'Import CSV into Spreadsheet
Set objWorkbook = objExcel.Workbooks.open(srccsvfile)
Set objWorksheet1 = objWorkbook.Worksheets(1)
'Adjust width of columns
Set objRange = objWorksheet1.UsedRange
objRange.EntireColumn.Autofit()
'This code could be used to AutoFit a select number of columns
'For intColumns = 1 To 17
' objExcel.Columns(intColumns).AutoFit()
'Next
'Make Headings Bold
objExcel.Rows(1).Font.Bold = TRUE
'Freeze header row
With objExcel.ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
objExcel.ActiveWindow.FreezePanes = True
'Add Data Filters to Heading Row
objExcel.Rows(1).AutoFilter
'set header row gray
objExcel.Rows(1).Interior.ColorIndex = 15
'-0.249977111117893
'Save Spreadsheet, 51 = Excel 2007-2010
objWorksheet1.SaveAs tgtxlsfile, 51
'Release Lock on Spreadsheet
objExcel.Quit()
Set objWorksheet1 = Nothing
Set objWorkbook = Nothing
Set ObjExcel = Nothing
source :http://www.tek-tips.com/viewthread.cfm?qid=1682555
Pipe doesn't equal Comma, Excel natively knows what to do with a CSV, but not with Pipe.
All is not lost, record your actions opening the file manually, once open highlight column A and click Data / Text To Columns, choose delimited and in the "other" box put a pipe then click next, choose the column formats (great to format numbers as text if you need to like Postcodes and phone numbers) then click finish.
Now stop the recorder and look at the code it generated. Port this over to your Excel object in your script.
Excel is a little picky when it comes to reading CSV files. If you have a delimited file with the extension .csv Excel will only open it correctly via the Open method if the delimiter is the character configured in the system's regional settings.
The Open method has optional parameters that allow you to specify a custom delimiter character (credit to #Jeeped for pointing this out):
set objWorkbook = objExcel.Workbooks.Open(srccsvfile, , , 6, , , , , "|")
You can also use the OpenText method (which will be used when recording the action as a macro):
objExcel.Workbooks.OpenText srccsvfile, , , 1, , , , , , , True, "|"
Set objWorkbook = objExcel.Workbooks(1)
Note that the OpenText method does not return a workbook object, so you must assign the workbook to a variable yourself after opening the file.
Important: either way your file must not have the extension .csv if your delimiter character differs from your system's regional settings, otherwise the delimiter will be ignored.

Change date format of a column in CSV file to yyyy-MM-dd using VBScript

I am trying to convert the date from 06-10-2009 00:00:00 to yyyy-MM-dd.
I need this for automated data import through Salesforce Apex Data Loader through command line.
Thus opening Excel manually and formatting the columns is out of question.
I have tried my hands on with following VBScript - but it didn't help.
Option Explicit
Dim objExcel1, objWB, strPathExcel1, objSheet1
Set objExcel1 = CreateObject("Excel.Application")
strPathExcel1 = "C:\Path\To\File\Details.csv"
Set objWB = objExcel1.Workbooks.Open(strPathExcel1)
Set objSheet1 = objWB.Worksheets(1)
objExcel1.Visible = True
objSheet1.Columns("E:E").NumberFormat = "yyyy-MM-dd"
objWB.Save
objWB.Close
objExcel1.Quit
I do not know any of VB Scripting at all. All I need to do is convert the date format of a CSV column into yyyy-MM-dd. Also I need to invoke the script from Windows Batch file. I would appreciate if someone briefly adds on how to invoke a VBScript from a Batch file.
This code will convert the date format using a TEXT formula
As per this MSFT link you should then use this CSV file in your application directly - if you re-open it in Excel the date field will inherit your regional date settings
change your file path, and cell range to suit
Dim objExcel1, objWB, strPathExcel1, objSheet1
Set objExcel1 = CreateObject("Excel.Application")
objExcel1.DisplayAlerts = False
strPathExcel1 = "C:\temp\book4.csv"
Set objWB = objExcel1.Workbooks.Open(strPathExcel1)
Set objSheet1 = objWB.Worksheets(1)
With objSheet1.Range("E1:E100")
.Columns.Offset(0, 1).Insert
.Offset(0, 1).FormulaR1C1 = "=IF(LEN(RC[-1])>0,TEXT(RC[-1],""yyyy-mm-d""),"""")"
.Offset(0, 1).Copy
.PasteSpecial -4163
.Columns.Offset(0, 1).Delete
End With
objWB.Save
objWB.Close
objExcel1.DisplayAlerts = True
objExcel1.Quit

Copy the content of last line from text file and paste in excel column

I wanted to write a batch file for following scenario:
I have multiple text file like 1.txt,2.txt...n.txt.
Now I want to copy the last line from text file and paste it in specified excel sheet colunm like coln B or H.
Can anyone help me?
Thanks
In VBScript you can do it like this:
Create your excel file
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\test.xls")
Go through your text files in a loop, open them and read the last line
Set n = 10 'the number of your files
For i = 0 To n
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(i & ".txt", ForReading)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
Loop
objFile.Close
Write the data stored in strLine to your excel file
objExcel.Application.Visible = True
objExcel.Workbooks.Add
objExcel.Cells(i, 1).Value = strLine
Next
Save and close your excel file
objExcel.ActiveWorkbook.Save "C:\test.xls"
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
I have not tested this code, it should just show you an idea how it could possibly work.

Resources