How to paste text with leading "0" in excel - excel

I have this code that pastes entire txt file contents to my active workbook but it loses leading "0" in cells:
Dim FileToOpen As Variant
Dim OpenBook As Workbook
FileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
OpenBook.Sheets(1).UsedRange.Select
Selection.NumberFormat = "#"
OpenBook.Sheets(1).UsedRange.Copy
ThisWorkbook.Worksheets("BOM").Range("C1").PasteSpecial xlPasteValues
OpenBook.Close False
End If
I tried to work around it by adding
OpenBook.Sheets(1).UsedRange.Select
Selection.NumberFormat = "#"
But it doesn't do the trick.
So how do I paste the contents and not lose leading "0"?

To do what you want, you cannot OPEN the file. You must IMPORT the file. That way you can designate the data as being text before Excel turns it into a numeric value. Once Excel turns it into a number, formatting alone will not recover the original textual value
eg, to import the file, use the Workbooks.OpenText method:
Application.Workbooks.OpenText _
Filename:=FileToOpen, _
DataType:=xlDelimited, _
comma:=True, Tab:=False, semicolon:=False, Space:=False, other:=False, _
fieldinfo:=Array(Array(1, xlTextFormat), Array(2, xlTextFormat))
Then you can do a simple copy/paste operation and the text property should be maintained.
eg:
ActiveSheet.UsedRange.Copy Destination:= 'your fully qualified destination
Putting it all together, something like:
Option Explicit
Sub due()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
FileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If FileToOpen <> False Then
Application.Workbooks.OpenText _
Filename:=FileToOpen, _
DataType:=xlDelimited, _
comma:=True, Tab:=False, semicolon:=False, Space:=False, other:=False, _
fieldinfo:=Array(Array(1, xlTextFormat), Array(2, xlTextFormat))
ActiveSheet.UsedRange.Copy ThisWorkbook.Worksheets("BOM").Range("C1")
ActiveWorkbook.Close False
End If
End Sub
Note that you will need an array argument in FieldInfo for each column you want to be parsed as other than General, and no arguments for non-existent columns. See Microsoft VBA Help for the Workbooks.OpenText method for more information.
Original CSV
Pasted Values

Please, try the next code. It will use a different way of opening the text file. If the number of columns is not constant, the code will firstly count them and then build an array able to make the file opening as you need:
Sub openAsTextTextFormat()
Dim FileToOpen As Variant, arrTXT, nrCol As Long, arr(), i As Long
Dim OpenBook As Workbook
FileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If FileToOpen <> False Then
'Check the number of text file columns:
arrTXT = Split(CreateObject("Scripting.FileSystemObject").OpenTextFile(FileToOpen, 1).ReadAll, vbLf)
nrCol = UBound(Split(arrTXT(0), vbTab))
'______________________________________
ReDim arr(nrCol) 'redim the format array
For i = 0 To nrCol
arr(i) = Array(1, 2) 'fill the format array with variant for TEXT Format!
Next
Workbooks.OpenText FileName:=FileToOpen, origin:=932, startRow:=1, DataType:=xlDelimited, _
other:=True, OtherChar:="|", FieldInfo:=arr()
Set OpenBook = ActiveWorkbook
Stop ' The code will stop here! Please, check if the text file has been open with the correct format.
OpenBook.Sheets(1).UsedRange.Copy ThisWorkbook.Worksheets("BOM").Range("C1")
OpenBook.Close False
End If
End Sub

You could try setting the format of the destination range.
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Dim rng As Range
FileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
Set rng = OpenBook.Sheets(1).UsedRange
With ThisWorkbook.Worksheets("BOM")
.Range("C1").Resize(rng.Rows.Count, rng.Columns.Count).NumberFormat = "#"
rng.Copy
.Range("C1").PasteSpecial xlPasteValues
End With
OpenBook.Close False
End If

You need to know how many digits are those numbers. This code, as example, makes all numbers to have 6 digits, so it adds leading zeros until len of string is 6.
Also, it will copy 1 column to another column.
Sub test()
Dim MiMatriz As Variant
Dim i As Long
Dim ZZ As Long
ZZ = 1 'first row where data is going to be pasted
MiMatriz = Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row).Value
For i = 1 To UBound(MiMatriz) Step 1
MiMatriz(i, 1) = "'" & Format(MiMatriz(i, 1), "000000")
Next i
Range("C" & ZZ & ":C" & ZZ + UBound(MiMatriz) - 1) = MiMatriz
Erase MiMatriz
End Sub
As you can see in the image below, column A would be the original and column C, numbers with leading zeros.
You can adapt this code to fit your needs.

Related

Copy pasting from different CSVs to one XLSX file

I am trying to succeed the following in VBA:
Open each file in the folder ( 1 by 1 )
Since all files are CSVs, I'd like to make them into more columns to gather the data I need.
I'd like to copy-paste these into one specific excel. These are around 300 rows.
In that specific Excel I'd like to have them pasted under each other.
What I have already tried:
The method to find all those files I need.
Make CSV datas into columns.
Copy-paste method.
Find the first empty row down under.
The problem is: I don't have enough knowledge for the macro to do it to all CSVs.
Please see my code below where I got so far:
Sub pm_logger()
Application.ScreenUpdating = False
Dim bookDest As Workbook
Dim bookFrom As Workbook
Dim lDestLastRow as Long
Dim sh As Worksheet
Workbooks.Open "P:\logs\logstorage.xlsx"
Workbooks.Open "P:\logs\logfile.csv"
Set bookDest = Workbooks("logstorage.xlsx")
Set bookFrom = Workbooks("logfile.csv")
bookFrom.Activate
Set sh = Worksheets(1)
With sh
Set Rng = .Range("A5:A305")
Set Rng = .Range(Rng, .Cells(.Rows.Count, Rng.Column).End(xlUp))
Rng.TextToColumns Destination:=Rng, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=False, _
Comma:=True, _
Space:=False, _
Other:=False, _
FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
TrailingMinusNumbers:=True
End With
bookFrom.Worksheets(1).Range("A5:K304").Copy
lDestLastRow = bookDest.Cells(bookDest.Rows.Count, "A").End(xlUp).Offset(1).Row
bookDest.Range("A" & xlDestLastRow).PasteSpecial Paste:=xlPasteValues
'Workbooks("logstorage.xlsx").Close SaveChanges:=True
Application.ScreenUpdating = True
End Sub
Thank you very much in advance!
To get this done, you first need a way to get all your .csv files loaded into your macro. This can be done a few ways, but I suggest a file picker to load them all into a collection:
Dim picker As Office.FileDialog
Dim mycsvs As New Collection
Dim file As Variant
Set picker = Application.FileDialog(msoFileDialogFilePicker)
With picker
.Filters.Clear
.Filters.Add "CSV files", "*.csv", 1
.AllowMultiSelect = True
.InitialFileName = "P:logs\"
If .Show = True Then
For Each file In .SelectedItems
mycsvs.Add file
Next file
End If
End With
Now you have the collection mycsvs which holds all the files you selected to be processed. Then all you need after that is to loop over them with the code you have already written:
Workbooks.Open "P:\logs\logstorage.xlsx"
For Each file In mycsvs
Set bookDest = Workbooks("logstorage.xlsx")
Set bookFrom = Workbooks.open(file)
'your code here from "Bookfrom.Activate"
bookFrom.Close SaveChanges:= False
Next file
'Workbooks("logstorage.xlsx").Close SaveChanges:=True

Set the cell format to text in excel before importing

i am importing multiple text files in excel using the Macro given at this site
it is working but say for example u have data as 0010 it is changing it to 10 i tried to modify the code by adding
Destination:=Range("A1").NumberFormatLocal = "#" in the script but it is giving error
texttocoloums method of range class failed
here is the original code
Sub CombineTextFiles()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
Set wkbTemp = Workbooks.Open(FileName:=FilesToOpen(x))
wkbTemp.Sheets(1).Copy
Set wkbAll = ActiveWorkbook
wkbTemp.Close (False)
wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
x = x + 1
While x <= UBound(FilesToOpen)
Set wkbTemp = Workbooks.Open(FileName:=FilesToOpen(x))
With wkbAll
wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
End With
x = x + 1
Wend
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
Consider the following code. Run it , it works, does what you want. Might be a bit slower (if you don't have any blank lines in any of your notepad files you can remove If Len(lineData) > 0 Then & the end if. to speed it up again) but I think it always worth keeping those lines in, incase if you do have empty rows in any of your notepad files.
I was also going to refer you to Python which can convert .txt files to Excel, keep the formatting without any extra work, simpler. Pretty native of it to do so. So If you have python it might be better to use that to convert your notepad files to excel en-masse (they are short scripts no matter which method you use there), but in VBA I've refered to this for keeping the formatting & leading zeros, and this to create the structure to import my files.
Sub doIt6()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim InputTextFile As Variant
Dim SourceDataFolder As String, OutputDataFolder As String
SourceDataFolder = "C:\Users\User\Documents\Source_Data2 - Copy"
OutputDataFolder = "C:\Users\User\Documents\Output_Data - Copy"
'Loop through each text file in source folder
InputTextFile = Dir(SourceDataFolder & "\*.txt")
While InputTextFile <> ""
Workbooks.OpenText FileName:=SourceDataFolder & "\" & InputTextFile, DataType:=xlDelimited, Tab:=True
Dim myFileName As Variant
Dim myFileNames As Variant
Dim wb As Workbook
'myFileNames = Application.GetOpenFilename( _
' filefilter:="Excel Files,*.xl*;*.xm*", _
' title:="Select Excel File to Open", _
' MultiSelect:=True)
myFileNames = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, title:="Text Files to Open")
If Not IsArray(myFileNames) Then Exit Sub
For Each myFileName In myFileNames
Set wb = Workbooks.Open(myFileName, False, False)
'StandaloneReportEdit()'Sub to very thoroughly edit reports
Dim fn As Integer
Dim MyData As String
Dim lineData As String, strData() As String, myFile As String
Dim i As Long, rng As Range
'Workbooks.OpenText Filename:=SourceDataFolder & "\" & InputTextFile, DataType:=xlDelimited, Tab:=True
Set rng = Range("A1")
' Lets not rely on Magic Numbers
fn = FreeFile
Open myFileName For Input As #fn
i = 1
Do While Not EOF(fn)
Line Input #fn, lineData
If Len(lineData) > 0 Then
strData = Split(lineData, "|")
rng.Cells(i, 1).Resize(1, UBound(strData) + 1) = strData
End If
i = i + 1
Loop
Close #fn
ActiveWorkbook.SaveAs FileName:=OutputDataFolder & "\" & Replace(ActiveWorkbook.Name, ".txt", ".xlsx"), FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
ActiveWorkbook.Close
InputTextFile = Dir
Next
'Save each output file in output folder / maybe put this inside the loop
'ActiveWorkbook.SaveAs FileName:=OutputDataFolder & "\" & Replace(ActiveWorkbook.Name, ".txt", ".xlsx"), FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
'ActiveWorkbook.Close
'InputTextFile = Dir
Wend
End Sub
*note: I am at work, (day job). have lost many urls I was referring to (they are in chrome history but with no time to check on any others, & I must get on with my work) to do this, but can I re-edit this post and dig them up for you tonight if you need.
Does this answer your question ?
You could also import with Python. You could do this : (put your directory name containing all your the text files in mypath between the ' ''s)
Your files (csv's or .txt files) are read into dataframes, significantly as dtype='object' , which is the KEY here to preserving their formatting fully and keeping leading 000's in ALL txt source files when using the method.
I know there are 10000 other ways to do it much more elegantly (such as here and elsewhere) but I'm super happy I did it like this using Python as well.
from os import walk
import pandas as pd
from pathlib import Path
mypath=r'C:\Users\user\Documents\Data_Souce4\New Folder (2)'
f = []
df=[]
for (dirpath, dirnames, filenames) in walk(mypath):
f.extend(filenames)
#print(f)
#print(f[2])
for f in f:
ab=print(mypath+"\\"+f) #you an remove this - was just for me to see whats going on
str_path = mypath+"\\"+f
path=Path(str_path)
print(path)
df = pd.read_csv(path, dtype=('object'), sep=r'\\t')
df.to_excel(mypath + "\\" + f + '.xls', index=True, header=True)
break

Attempting to continue my list import, instead it over overwrites my previous import in VBA

I've borrowed some code from a post on this site already and made my own. However I'm running into a problem where the multiple files in my folder path are importing OVER the previous import instead of below the created list.
What I'm trying to achieve is importing data from multiple files in a specific folder location. After pursing through each file, the next import data should be placed under the previous import data in the worksheet.
Any insights on how to fix?
Thanks so much!
cwegz
Option Explicit
Const FOLDER_PATH = "Test Folder Path/" 'REMEMBER END BACKSLASH
Sub ImportWorksheets()
'=============================================
'Process all Excel files in specified folder
'=============================================
Dim sFile As String 'file to process
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim rowTarget As Long 'output row
rowTarget = 2
'check the folder exists
If Not FileFolderExists(FOLDER_PATH) Then
MsgBox "Specified folder does not exist, exiting!"
Exit Sub
End If
'reset application settings in event of error
On Error GoTo errHandler
Application.ScreenUpdating = False
'set up the target worksheet
Set wsTarget = Sheet1
'loop through the Excel files in the folder
sFile = Dir(FOLDER_PATH & "*.xls*")
Do Until sFile = ""
'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
Set wsSource = wbSource.Worksheets(1) 'EDIT IF NECESSARY
'import the data
With wsTarget
.Columns("A").Value = wsSource.Columns("A").Value 'this one works
.Columns("B").Value = wsSource.Columns("C").Value 'this one works
'.Range("A1" & rowTarget).Value = wsSource.Columns("A").Value
'.Range("B1" & rowTarget).Value = wsSource.Columns("C").Value
'optional source filename in the last column
.Range("N" & rowTarget).Value = sFile
End With
'close the source workbook, increment the output row and get the next file
wbSource.Close SaveChanges:=False
rowTarget = rowTarget + 1
sFile = Dir()
Loop
errHandler:
On Error Resume Next
Application.ScreenUpdating = True
'tidy up
Set wsSource = Nothing
Set wbSource = Nothing
Set wsTarget = Nothing
Set Selection = Nothing
Sheets("Pull").Select
Columns("B:B").Select
Selection.TextToColumns Destination:=Range("C1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="#", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Set Selection = Nothing
Sheets("Pull").Select
Columns("D:D").Select
Selection.TextToColumns Destination:=Range("D1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:=";", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Set Selection = Nothing
Sheets("WhiteList").Select
Columns("A:A").Select
Selection.TextToColumns Destination:=Range("K1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="#", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Set Selection = Nothing
Sheets("Summary").Select
End Sub
Here's one approach, which should work if your data tables are consistent and contain no blank rows/columns.
Option Explicit
Const FOLDER_PATH = "Test Folder Path\" 'REMEMBER END BACKSLASH
Sub ImportWorksheets()
Dim sFile As String 'file to process
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet, rngData As Range, numRows As Long
Dim rowTarget As Long 'output row
If Not FileFolderExists(FOLDER_PATH) Then
MsgBox "Specified folder does not exist, exiting!"
Exit Sub
End If
On Error GoTo errHandler
Application.ScreenUpdating = False
Set wsTarget = Sheet1
'get first empty row, assuming colA always has values
rowTarget = wsTarget.Cells(Rows.Count, 1).End(xlUp).Row + 1
sFile = Dir(FOLDER_PATH & "*.xls*")
Do Until sFile = ""
Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
Set wsSource = wbSource.Worksheets(1)
Set rngData = wsSource.Range("A1").CurrentRegion '<< assumes no empty rows/columns in your data table
numRows = rngData.Rows.Count '<<
With wsTarget
.Cells(rowTarget, "A").Resize(numRows, 1).Value = rngData.Columns(1).Value
.Cells(rowTarget, "B").Resize(numRows, 1).Value = rngData.Columns(3).Value
'etc etc
.Cells(rowTarget, "N").Value = sFile 'optional source filename in the last column
End With
wbSource.Close SaveChanges:=False
rowTarget = rowTarget + numRows '<<
sFile = Dir()
Loop
'snipped....
End Sub

How to import multiple text files into columns of single excel worksheet

I have been trying to figure out how to take several hundred tab-delimited text files and import the data into subsequent columns of a single excel worksheet. The text files contain I(V) data with two columns and a header. I have found code/manipulated it to be able to remove the header and import into individual worksheets within a workbook but would like to be able to get the two columns of data from each worksheet into a single worksheet (i.e. columns from first text file to columns A & B of one worksheet, columns from second text file to columns C & D, etc.). Here is the code I am currently using:
Sub CombineTextFiles()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
wkbTemp.Sheets(1).Copy
Set wkbAll = ActiveWorkbook
wkbTemp.Close (False)
wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=True, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
Rows("1:20").Select
Selection.Delete Shift:=xlUp
x = x + 1
While x <= UBound(FilesToOpen)
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
With wkbAll
wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
Rows("1:20").Select
Selection.Delete Shift:=xlUp
End With
x = x + 1
Wend
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
Here is an example of one of my I(V) data files:
Notes:
Timestamp: 7/19/2018 8:36:11 AM
Channel: Channel A
NPLC: 1
Current Limit: 0.010000
Pulse Mode: 0
Bias Pulses: 1
Bias Level: 0.000000
Settling Time: 0.500000
Voltage (V) Current (A)
-1.00000E+0 -6.95885E-7
-9.50000E-1 -6.47828E-7
-9.00000E-1 -6.06955E-7
-8.50000E-1 -5.53913E-7
-8.00000E-1 -5.00038E-7
-7.50000E-1 -4.51646E-7
-7.00000E-1 -4.02903E-7
-6.50000E-1 -3.58851E-7
-6.00000E-1 -3.19926E-7
-5.50000E-1 -2.73332E-7
-5.00000E-1 -2.33349E-7
-4.50000E-1 -1.99018E-7
-4.00000E-1 -1.62825E-7
-3.50000E-1 -1.31703E-7
-3.00000E-1 -1.04510E-7
-2.50000E-1 -8.06238E-8
-2.00000E-1 -5.88286E-8
-1.50000E-1 -4.14340E-8
-1.00000E-1 -2.58151E-8
-5.00000E-2 -1.24138E-8
0.00000E+0 5.52116E-11
5.00000E-2 1.26769E-8
1.00000E-1 2.64685E-8
1.50000E-1 4.17401E-8
2.00000E-1 5.97095E-8
2.50000E-1 7.98343E-8
3.00000E-1 1.02119E-7
3.50000E-1 1.28176E-7
4.00000E-1 1.57270E-7
4.50000E-1 1.89915E-7
5.00000E-1 2.29916E-7
5.50000E-1 2.72104E-7
6.00000E-1 3.35173E-7
6.50000E-1 4.53464E-7
7.00000E-1 6.12379E-7
7.50000E-1 7.97423E-7
8.00000E-1 9.75624E-7
8.50000E-1 1.16841E-6
9.00000E-1 1.34435E-6
9.50000E-1 1.52710E-6
1.00000E+0 1.75166E-6
1.00000E+0 1.81262E-6
9.50000E-1 1.72918E-6
9.00000E-1 1.63206E-6
8.50000E-1 1.52714E-6
8.00000E-1 1.42523E-6
7.50000E-1 1.32162E-6
7.00000E-1 1.21624E-6
6.50000E-1 1.11347E-6
6.00000E-1 1.00770E-6
5.50000E-1 9.05824E-7
5.00000E-1 8.08058E-7
4.50000E-1 7.09499E-7
4.00000E-1 6.14927E-7
3.50000E-1 5.26256E-7
3.00000E-1 4.38557E-7
2.50000E-1 3.53943E-7
2.00000E-1 2.74731E-7
1.50000E-1 1.98096E-7
1.00000E-1 1.27457E-7
5.00000E-2 6.16247E-8
0.00000E+0 -8.63841E-11
-5.00000E-2 -5.78634E-8
-1.00000E-1 -1.15769E-7
-1.50000E-1 -1.73858E-7
-2.00000E-1 -2.33503E-7
-2.50000E-1 -2.94364E-7
-3.00000E-1 -3.59336E-7
-3.50000E-1 -4.24816E-7
-4.00000E-1 -4.92460E-7
-4.50000E-1 -5.61514E-7
-5.00000E-1 -6.32542E-7
-5.50000E-1 -7.06702E-7
-6.00000E-1 -7.83559E-7
-6.50000E-1 -8.63077E-7
-7.00000E-1 -9.49685E-7
-7.50000E-1 -1.03839E-6
-8.00000E-1 -1.12932E-6
-8.50000E-1 -1.22503E-6
-9.00000E-1 -1.31770E-6
-9.50000E-1 -1.42892E-6
-1.00000E+0 -1.53654E-6
None of the header information is needed, which is why I am currently just deleting the first 20 rows. I have basic programming experience but very little with VBA. Any help with this particular problem is greatly appreciated!
-Tory
Try so:
Sub CombineTextFiles()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
Set wkbAll = ActiveWorkbook
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
iDestCol=1
For x = 0 to Ubound(FilesToOpen)
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
wkbTemp.Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=True, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
wbkTemp.Range("A:B").Copy Destination:=wkbAll.Cells(1, iDestCol)
wkbTemp.Close (False)
iDestCol = iDestCol + 2
Next
Rows("1:20").Delete Shift:=xlUp
ExitHandler:
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
So, I managed to get two macros coded to do what I need. I have one for pulling the data in from selected text files into individual sheets and another to consolidate the sheets into columns of a single sheet. The code for the first macro is here:
Sub TextToSheets()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
Name = Dir(FilesToOpen(x))
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
wkbTemp.Sheets(1).Copy
Set wkbAll = ActiveWorkbook
wkbTemp.Close (False)
wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=True, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
Range("A19:B19").Select
ActiveCell.FormulaR1C1 = Name
Range("A20").Select
ActiveCell.FormulaR1C1 = "Voltage (V)"
Range("B20").Select
ActiveCell.FormulaR1C1 = "Current (A)"
Rows("1:18").Select
Selection.Delete Shift:=xlUp
x = x + 1
While x <= UBound(FilesToOpen)
Name = Dir(FilesToOpen(x))
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
With wkbAll
wkbTemp.Sheets(1).Move after:=.Sheets(.Sheets.Count)
.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
Range("A19:B19").Select
ActiveCell.FormulaR1C1 = Name
Range("A20").Select
ActiveCell.FormulaR1C1 = "Voltage (V)"
Range("B20").Select
ActiveCell.FormulaR1C1 = "Current (A)"
Rows("1:18").Select
Selection.Delete Shift:=xlUp
End With
x = x + 1
Wend
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
And for the second here:
Sub CombineSheetsToColumns()
Application.DisplayAlerts = False
On Error Resume Next
Sheets("Summary").Delete
Application.DisplayAlerts = True
n = Application.Worksheets.Count
Sheets.Add.Name = "Summary"
Sheets("Summary").Move after:=Worksheets(Worksheets.Count)
Set MerPos = Range(Cells(1, 2), Cells(1, 3))
Dim sh As Worksheet
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> "Summary" And sh.Name <> Sheets(n + 1).Name Then
Set col = Columns(Columns.Count).End(xlToLeft)
sh.Range("A:A,B:B").Copy Destination:=Sheets("Summary").Range(col, col).Offset(0, 1)
MerPos.Select
Selection.Merge
Set MerPos = Range(MerPos.Offset(0, 1), MerPos.Offset(0, 2))
End If
Next sh
Columns("A:A").Select
Selection.Delete Shift:=xlToLeft
Sheets("Summary").Select
Cells.HorizontalAlignment = xlCenter
Columns.AutoFit = xlColumn
End Sub
I added a few lines for adding text and formatting but shouldn't be too hard to get it working for whatever you may need to use it for. Thanks for all the help!
If you want to copy/paste data across a sheet, run the code below.
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
Set folder = fso.GetFolder("C:\Users\Excel\Desktop\Coding\LinkedIn\Import All Text Files Into One Single Sheet with File Name in Column A\")
' set the starting point to write the data to
'Set cl = ActiveSheet.Cells(1, 1)
Dim sht As Worksheet
Dim LastRow As Long
Set sh = ActiveSheet
' Loop thru all files in the folder
For Each file In folder.Files
' Write file-name
LastRow = sh.Cells(sh.Rows.Count, "A").End(xlUp).Row + 1
Range("A" & LastRow).Select
ActiveCell = file.Name
' open the file
Set txtFile = fso.OpenTextFile(file)
col = 2
Do While Not txtFile.AtEndOfStream
dat = Application.Transpose(Application.Index(Split(txtFile.ReadLine, ","), 1, 0))
sh.Cells(LastRow, col).Resize(UBound(dat), 1) = dat
col = col + 1
Loop
' Clean up
txtFile.Close
'Range(cl.Address).Offset(1, 0).Select
Next file
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
If you want to copy/paste data down a sheet, run the code below.
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
Set folder = fso.GetFolder("C:\Users\Excel\Desktop\Coding\LinkedIn\Import All Text Files Into One Single Sheet with File Name in Column A\")
' set the starting point to write the data to
Set cl = ActiveSheet.Cells(2, 1)
' Loop thru all files in the folder
For Each file In folder.Files
' Write file-name
cl.Value = file.Name
' Open the file
Set FileText = file.OpenAsTextStream(ForReading)
' Read the file one line at a time
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine
' Parse the line into | delimited pieces
Items = Split(TextLine, "|")
' Put data on one row in active sheet
For i = 0 To UBound(Items)
cl.Offset(0, 1 + i).Value = Items(i)
Next
' Move to next row
Set cl = cl.Offset(1, 0)
Loop
' Clean up
FileText.Close
Next file
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub

TextToColumns function uses wrong delimiter

I am trying to open all csv (separator is semicolon) files in a directory and this is the code that I think should work:
Sub test()
Dim MyFile As String
Dim MyDir As String
MyDir = Application.ActiveWorkbook.Path
MyFile = Dir(MyDir & "\" & "*.csv")
'set current directoy
ChDir MyDir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0
Do While MyFile <> ""
Workbooks.Open (MyFile)
'Parse it using semicolon as delimiters
Range(Range("A1"), Range("A1").End(xlDown)).TextToColumns _
DataType:=xlDelimited, _
ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=True, Comma:=False, Space:=False, Other:=False '
'next file in directory
MyFile = Dir()
Loop
End Sub
But strangely, it also uses comma as a separator as well. I can see that if I debug the TextToColumns line.
So for a csv file like
test;test,test
I would expect an output of
test test,test
But I actually get
test test
Why? Is there something wrong with my Excel settings?
Thanks!
The problem is with this line
Workbooks.Open (MyFile)
The moment you open the file in Excel, it is opened in this format as it is a Comma Delimited File
And then when the .TextToColumns code runs it replaces Column B data with the "test" which is after ; in Column A.
Try this
Let's say your csv file looks like this
Now try this code. Once you understand how it works, simply adapt this in your code. I have commented the code so that you will not have a problem understanding it.
Sub Sample()
Dim wb As Workbook, ws As Worksheet
Dim MyData As String, strData() As String
Dim myFile As String
Dim lRow As Long
'~~> Replace this with your actual file
myFile = "C:\Users\Siddharth\Desktop\test.csv"
'~~> open text file in memory and read it in one go
Open myFile For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
'~~> Add a new workbook
Set wb = Workbooks.Add
'~~> Work with the 1st sheet
Set ws = wb.Sheets(1)
With ws
'~~> Copy the array to worksheet
.Range("A1").Resize(UBound(strData), 1).Value = strData
'~~> get the last row of the data
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
'~~> Use text To columns now
.Range("A1:A" & lRow).TextToColumns DataType:=xlDelimited, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=True, _
Comma:=False, _
Space:=False, _
Other:=False '
End With
End Sub
And this is what you get
EDIT: The other option that you have is to rename the csv file and then open it as suggested in Open csv file delimited by pipe character “|” or not common delimiter

Resources