Locate Dates within .txt file and Format them - string

First off, I know there's a million questions about formatting dates, but I have not found a solution that works with my situation.
We are given a .csv file, and due to requirements, we must modify the file in a couple of ways.
Firstly, we run a VBA on the file in order to change the delimiter from "," to "|" (we have this working) using:
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\Z00393885\Desktop\csvStuff\"&myVar, ForReading)
count = 0
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
strReplacer = Chr(34) & "," & Chr(34)
strLine = Replace(strLine, strReplacer, "|")
strLine = Replace(strLine, chr(34), "")
strNewText = strNewText & strLine & vbCrLF
count = count + 1
Loop
Print (count - 1)
objFile.Close
Set objFile = objFSO.OpenTextFile("C:\Users\Z00393885\Desktop\csvStuff\"&myVar, ForWriting)
objFile.WriteLine "BOF" & vbCrLF & now() & vbCrLF & (count - 1) & vbCrLF & strNewText & "EOF"
objFile.Close
The second requirement is the one that's giving me trouble, I have to look for every Date that is present (they are formatted: 11/8/2017 1:30 EST and lie within the 10th and 11th columns) and format the date so that it would be 11/08/2017 (we need to remove the Time as well as make sure that the day and month has a 0 if its only a single digit)
Is this doable within the Do Until loop? or would it be better to have a separate function to take care of that part. Either way, I am not even sure where to start with manipulating Dates within a file like this and not just a variable
EDIT: here is some of the .csv file
BOF
11/1/2017 12:08:21 PM
3
Course Code|Home Org|...|Release Date|Effective Date|...|Web Address
123|TAD Sites|...|10/31/2017 00:00:00 EDT|11/14/2017 00:00:00 EDT|...|http://URL
456|DAT Sites|...|11/5/2017 00:00:00 EDT|11/5/2017 00:00:00 EDT|...|http://URL
EOF

One thing you could do is split the original line into the columns, then you only need to consider the 10th and 11th columns:
Dim myArray() As String
'...
strLine = objFile.ReadLine
'Current delimiter is quote-comma-quote
strReplacer = Chr(34) & "," & Chr(34)
'Replace current delimiter with a pipe delimiter
strLine = Replace(strLine, strReplacer, "|")
'Remove any remaining quote marks
strLine = Replace(strLine, Chr(34), "")
'Split line using pipe delimiter
myArray = Split(strLine, "|")
'Convert column 10
myArray(9) = Format(CDate(Left(myArray(9), InStr(myArray(9), " ") - 1)), "mm/dd/yyyy")
'Convert column 11
myArray(10) = Format(CDate(Left(myArray(10), InStr(myArray(10), " ") - 1)), "mm/dd/yyyy")
'Join line back together with pipe delimiter
strLine = Join(myArray, "|")
'Create one huge string containing all lines in file
strNewText = strNewText & strLine & vbCrLF
'...
To use this as VBScript will require a few minor changes:
'Dim myArray() As String
Dim myArray
'...
strLine = objFile.ReadLine
'Current delimiter is quote-comma-quote
strReplacer = Chr(34) & "," & Chr(34)
'Replace current delimiter with a pipe delimiter
strLine = Replace(strLine, strReplacer, "|")
'Remove any remaining quote marks
strLine = Replace(strLine, Chr(34), "")
'Split line using pipe delimiter
myArray = Split(strLine, "|")
'Convert column 10
'myArray(9) = Format(CDate(Left(myArray(9), InStr(myArray(9), " ") - 1)), "mm/dd/yyyy")
myArray(9) = FormatDateTime(CDate(Left(myArray(9), InStr(myArray(9), " ") - 1)), 0)
'Convert column 11
'myArray(10) = Format(CDate(Left(myArray(10), InStr(myArray(10), " ") - 1)), "mm/dd/yyyy")
myArray(10) = FormatDateTime(CDate(Left(myArray(10), InStr(myArray(10), " ") - 1)), 0)
'Join line back together with pipe delimiter
strLine = Join(myArray, "|")
'Create one huge string containing all lines in file
strNewText = strNewText & strLine & vbCrLF
'...
I don't use VBScript myself, but I believe the FormatDateTime function will give you what you want as output. It seems to be locale-specific, but I assume you use mm/dd/yyyy format as standard in your location.

Have you thought about running a "text to column" function, simply altering the formats to the date columns, then outputting the file? This might be a lot easier than searching for characters and altering them the way you are doing.
With Range(pass the range here)
.TextToColumns Destination:=Range("A1"), 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), Array(..., ...),_
TrailingMinusNumbers:=True
Columns("x:x").NumberFormat = "mm/dd/yyyy"
From here you can save the file.
EDIT:
One caveat: you need to hard code the number of columns you will end up with into the array.
For example, if each row of the file contains 4 sections, you would use:
Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1)), TrailingMinusNumbers:=True

Related

I want to format my csv file, from an excel export

I have a problem with the date format in the new exported csv file.
If I export a range from an excel file, then the date format is dd/mm/yyyy but i need dd/mm/yyyy hh:nn.
If I changed the format in the original excel file to the right form, then the most values in the csv show the right format except the date-value e.g. 18.08.2021 00:00.
So if the time is 00:00 then only the dd/mm/yyyy format appears at that row and this format is incompatible to the database.
(i opened it in excel and in the editor and it appeared the same problem)
can someone help me?
Dim ws As Worksheet, fd As FileDialog, rngTest As Range, rngExport As Range, fltr As FileDialogFilter
Dim start As Long
start = 2
'Nach jeweiliger Zeit wird Datenreihe (start ab) ausgewählt
If Time < TimeValue("11:15") Then
Do Until Daten.Range("ov" & start) = Date + 1
start = start + 1
Loop
ElseIf Time < TimeValue("11:15") Then
Do Until Daten.Range("ov" & start) = Date + 2
start = start + 1
Loop
Else: start = 2
End If
start = start + 1
'Worksheet auf dem die Daten stehen
Set ws = Worksheets("Daten")
'Zelle die auf Inhalt überprüft werden soll
Set rngTest = ws.Range("ov2")
'Bereich der exportiert wird
Set rngExport = ws.Range("ov" & start & ":ow10000")
' ws.Range("ov" & start & ":ov5000").NumberFormat = "dd/mm/yyyy hh:mm"
If rngTest.Text <> "" Then
Set fd = Application.FileDialog(msoFileDialogSaveAs)
'Filename
fd.InitialFileName = "LG" & " " & Diagramm.Range("a5").Value & " " & "RZ" & " " & Format(Date, "mmmm") & " " & Format(Date, "yyyy") & "_" & "MW" & "_" & "ab" & " " & Daten.Range("ov" & start - 1).Value
' Application.Dialogs(xlDialogSaveAs).Show filenameComplete
With fd
.Title = ""
'Filterindex für CSV-Dateien ermitteln
For i = 1 To .Filters.count
If .Filters(i).Extensions = "*.csv" Then
.FilterIndex = i
Exit For
End If
Next
'Wenn OK geklickt wurde starte Export
If .Show = True Then
ExportRangeAsCSV rngExport, ";", .SelectedItems(1)
End If
End With
End If
End Sub
'Hier werden die Werte in eine CSV-Datei eingefügt und gespeichert
Sub ExportRangeAsCSV(ByVal rng As Range, delim As String, filepath As String)
Dim arr As Variant, line As String, csvContent As String, fso As Object, csvFile As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set csvFile = fso.OpenTextFile(filepath, 2, True)
arr = rng.Value 'Filter
If IsArray(arr) Then
' um die Überschrift im CSV oben einzufügen
Dim col As Range
For Each col In rng.Columns
If Len(line) > 0 Then line = line & delim
line = line & """" & rng.Parent.Cells(1, col.column) & """"
Next
csvContent = line & vbNewLine
'um die Werte ins CSV einzufügen
For r = 1 To UBound(arr, 1)
line = ""
For c = 1 To UBound(arr, 2)
If c < UBound(arr, 2) Then
line = line & """" & arr(r, c) & """" & delim
Else
line = line & """" & arr(r, c) & """"
End If
Next
csvContent = csvContent & line & vbNewLine
Next
csvFile.Write (csvContent)
csvFile.Close
Else
MsgBox "Bereich besteht nur aus einer Zelle!", vbExclamation
End If
Set fso = Nothing
Set csvFile = Nothing
End Sub
The Range("ov").value is the date and Range("ow").value the amount (double)
As you are already writing the CSV-File manually, I would suggest to introduce a function that converts your cell content as a string. You could use this routine for multiple purposes, eg format numbers (decimals, number of digits...), get rid of unwanted characters in as string (eg Newlines, semicolon, quote characers)...
Just to give you an idea:
Function FormatCellValue(v As Variant) As String
If IsDate(v) Then
FormatCellValue = Format(v, "dd.mm.yyyy hh:mm")
ElseIf VarType(v) = vbDecimal Then
FormatCellValue = Format(v, "#####.00")
ElseIf VarType(v) = vbString Then
v = Replace(v, vbCr, " ")
v = Replace(v, vbLf, " ")
v = Replace(v, ";", ",")
v = Replace(v, """", "'")
FormatCellValue = v
Else
FormatCellValue = v
End If
End Function
And in your existing code, simply write
line = line & """" & FormatCellValue(arr(r, c)) & """"
Update
If you want to write only strings with quote and dates (and numbers) without, you could add the quotes in the FormatCell-function: In the Vartype = vbString-branch, write
FormatCellValue = """" & v & """"
and change the call to
line = line & FormatCellValue(arr(r, c))
Excel really sucks at formatting numbers because the internal systems keep the stored value and displayed value separately. So what you see is not what will end up in the file when you save. To force excel to actually apply the formatting to the stored value, I use quotes to turn numbers & dates into strings. Like [A1].formula = "=""" & [A1].Value & """" which would turn a cell containing the number 100.00 into ="100.00" a literal string that excel can't reformat.
For your date format situation, you can do [A1].formula = "=""" & Format([A1].Value, "dd/mm/yyyy hh:nn") & """". Which will force excel to save the cell value in the specified format and ensure the output csv is in that format.
Here is a function that I have used previously to change a 2D array of values into an array of formulas as described above.
Private Function ForceString(ByRef InputArr As Variant) As Variant
Dim OutputArr() As Variant
OutputArr = InputArr
Dim i As Long, j As Long
For i = LBound(OutputArr) To UBound(OutputArr)
For j = LBound(OutputArr, 2) To UBound(OutputArr, 2)
If Len(OutputArr(i, j)) < 255 Then
OutputArr(i, j) = "=""" & OutputArr(i, j) & """"
Else
Dim k As Long, Tmp As String
Tmp = "="
For k = 1 To Len(OutputArr(i, j)) Step 255
Tmp = Tmp & IIf(k <> 1, "&", "") & """" & Mid(OutputArr(i, j), 1, 255) & """"
Next k
OutputArr(i, j) = Tmp
End If
Next j
Next i
ForceString = OutputArr
End Function
The If/Else in the middle is due to the limitation in excel about a literal string inside a formula not being allowed to have more than 255 characters. In those cases, it just has to be split up into multiple strings, but the output value is still the same.

Passing Variables and Table Data to a Text File Using VBA

I need to create a text file, each line of which consists of formatted values taken from 3 different places. I am able to create the file and pass the static variable and user input variables to the file, but I cannot seem to pass the row data from the table to the file.
RoutingNum is a single cell
Chkdate and ChkNum are taken from user input
AcctNum and Amt are from a table <-------------this is the problem.
The table has only two columns
AcctNum and Amt are named ranges in the table.
Each line of the file should look like this:
linetext = _
RoutingNum & _
Format(AcctNum, "00000000000000") & _
Format(ChkDate, "yymmdd") & _
Format(ChkNum, "0000000000") & _
Format(Amt, "00000000")
Here is what I have:
Dim strPath As String
strPath = wsEngine.Range("Path") & _
Format(wsEngine.Range("ChkDate"), "yymmdd") & _
Format(Time(), "hhmmss") & _
".txt"
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.createtextfile(strPath)
linetext = _
RoutingNum & _
Format(AcctNum, "00000000000000") & _
Format(ChkDate, "yymmdd") & _
Format(ChkNum, "0000000000") & _
Format(Amt, "00000000")
For i = 1 To wsAccts.Range("tbldata").Rows.Count
a.WriteLine linetext
Next i
a.Close
I am unable to insert AcctNum or Amt into each line. The rest of linetext is working.
I could use help to loop through the table and insert the cell values from each row into linetext.
Your code needs some modifications as below:
For i = 1 To wsAccts.Range("tbldata").Rows.Count
AcctNum = wsAccts.Range("tbldata").Cells(i, 1).Value 'First column
Amt = wsAccts.Range("tbldata").Cells(i, 2).Value 'Second column
linetext = _
RoutingNum & _
Format(AcctNum, "00000000000000") & _
Format(ChkDate, "yymmdd") & _
Format(ChkNum, "0000000000") & _
Format(Amt, "00000000")
a.WriteLine linetext
Next i
You obviously need to map appropriate variable to fill data from table.
Got it.
I needed to place both linetext, and the variables AcctNum and Amt, inside the loop.
It works perfectly. Thank you.

VBA How to use mid function in option explicit

I have a code , it loops through the destinated folder and every single file in the folder.
i have 2 questions
1) how can i modify this code and add it into my main code so that it would work without having compile error for not declaring the variables
For Each cell In Range("B1", Cells(Rows.count, "B").End(xlUp))
With cell
CodeExists = InStr(1, .Value, "testflow")
'Check that "Code:" exists
If CodeExists > 0 Then
.Value = Mid(.Value, CodeExists + 18, 3)
End If
End With
Next
2) if question 1 can't be done,
wks.Cells(BlankRow, 6).Replace What:="hometmastresh", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
wks.Cells(BlankRow, 6).Value = WorksheetFunction.Transpose(Split(wks.Cells(BlankRow, 6), "_"))
i would like to know how i can modify these 2 codes so that i can split my original string: "hometmastresh_enciivedexterXXtresh_tepootsXXXXXXXXXXXXXXtepootFile" that is currently in row E with "X" being unknown numbers and the fact that it will be different in every file.
i would like to split the original string into "XX" into Row F and "XXXXXXXXXXXXXX" into Row G respectively
i am still getting "01tresh_tepoots20191204756890tepootFile"
So after you have got the text using .Find, you can use Split. For example
Dim s As String
s = Split("01tresh_tepoots20191204756890tepootFile", "tepoot")(1)
s = Mid(s, 2, 8) & " " & Right(s, 6)
Debug.Print s
Edit
Your code
If Not aCell Is Nothing Then
aCell.Formula = Replace(aCell.Formula, , "")
s = Split(aCell.Value, "tepoots")(1)
End If
should be as shown below. This will put "20191204 756890" or whatever the number is in the cell.
If Not aCell Is Nothing Then
s = Split(aCell.Value, "tepoots")(1)
s = Mid(s, 2, 8) & " " & Right(s, 6)
aCell.Value = s
End If
Use Left/Right to get the ends of the string and concatenate them with a space
Dim v As String
'...
'...
If CodeExists > 0 Then
v = Mid(.Value, CodeExists + 18, 3)
.Value = Left(v, 8) & " " & Right(v, 6)
End If

Convert a txt file that uses space delimiter to tab delimiter

I have an excel file that is importing pricing from various txt files that are automatically generated by a third party. I hit a road block with one of the txt files because it uses space delimited whereas the others use tab. Because of the space delimited, when i split the data i get different values in each column.
Here is what I have so far to open and read the text file
usFileName = PathName & "\" & "Prices.txt"
If fs.FileExists(usFileName) Then
Set US = fs.OpenTextFile(usFileName, 1)
theData = US.ReadLine
getDate = Split(theData, Chr(0))
curDate = Trim(Left(getDate(0), 10))
If curDate = ActiveSheet.Range("Sheet_Date") Then
Do While Not US.AtEndOfStream
On Error Resume Next
Ln = US.ReadLine
Cols = Split(Ln, " ")
Price = Trim(Cols(7))
NameTrim = Trim(Replace(Cols(1), "USO-", ""))
CellName = Replace(NameTrim, "-", "_") & "_" & Trim(Cols(2))
If ActiveSheet.Range(CellName) Is Nothing Then
''Do Nothing here
On Error Resume Next
Else
Set TxtRng = ActiveSheet.Range(CellName)
If TxtRng = ActiveSheet.Range(CellName) Then
TxtRng.Value = Price
End If
End If
Loop
Else
MsgBox ("The current sheet date does not match the US file import date.")
End If
US.Close
Else
MsgBox ("The file Prices.txt does not exist.")
End If
This is what the txt file looks like:
01/11/2019 06:00 PM USO-FOX-USO E10 8.9929 0.0000
01/11/2019 06:00 PM USO-FOX-USO CON8HE10 1.3212 -0.0244
01/11/2019 06:00 PM USO-FOX-USO CON8HE10TT 1.3232 -0.0244
And this is what the Cols variable looks like.
Try
Sub Test()
Dim PathName As String
Dim usFileName As String
PathName = "Your path"
usFileName = PathName & "\" & "Prices.txt"
Workbooks.OpenText Filename:=usFileName, _
StartRow:=1, DataType:=xlFixedWidth, FieldInfo:=Array(Array(0, 1), _
Array(19, 1), Array(32, 1), Array(48, 1), Array(55, 1))
End Sub
You can try removing spaces and replacing them this way:
Ln = US.ReadLine
Do While (InStr(Ln, " ") > 0)
Ln = Replace(Ln, " ", " ")
Loop
'The only problem I see is the case where you have Time (6:00 PM) this
' would replace the space with Tab. in that case, I would do the following:
Ln = Replace(Ln, " PM", "PM")
Ln = Replace(Ln, " AM", "AM")
Ln = Replace(Ln, " ", vbTab)
'And then put them back
Ln = Replace(Ln, "PM", " PM")
Ln = Replace(Ln, "AM", " AM")
'Finally, split the columns
Cols = Split(Ln, vbTab)
If you want to try with fixed width then do the following (after Ln = US.Readline):
'01/11/2019 06:00 PM USO-FOX-USO E10 8.9929 0.0000
'Do the following only if (InStr(Ln, " ") > 0)
strCol1 = Mid(Ln, 1, 21)
strCol2 = Mid(Ln, 22, 13)
strCol3 = Mid(Ln, 35, 13)
strCol4 = Mid(Ln, 48, 11)
strCol5 = Mid(Ln, 59, Len(Ln))

Open CSV file via VBA (performance)

Obviously, this question has been asked many times. The normal procedure:
Workbooks.Open (ActiveWorkbook.Path & "\Test.csv")
won't parse the CSV correctly (having many rows in one cell)
Thanks to Lernkurve, I can use his function to get it right: Opening semicolon delimited CSV file
Sub ImportCSVFile(filepath As String)
Dim line As String
Dim arrayOfElements
Dim linenumber As Integer
Dim elementnumber As Integer
Dim element As Variant
linenumber = 0
elementnumber = 0
Open filepath For Input As #1 ' Open file for input
Do While Not EOF(1) ' Loop until end of file
linenumber = linenumber + 1
Line Input #1, line
arrayOfElements = Split(line, ";")
elementnumber = 0
For Each element In arrayOfElements
elementnumber = elementnumber + 1
Cells(linenumber, elementnumber).Value = element
Next
Loop
Close #1 ' Close file.
End Sub
This however is not fast (I have files with thousands of columns) and my question is:
Is there any native way to open CSV files in Excel with right parsing?
Workbooks.Open does work too.
Workbooks.Open ActiveWorkbook.Path & "\Temp.csv", Local:=True
this works/is needed because i use Excel in germany and excel does use "," to separate .csv by default because i use an english installation of windows. even if you use the code below excel forces the "," separator.
Workbooks.Open ActiveWorkbook.Path & "\Test.csv", , , 6, , , , , ";"
and Workbooks.Open ActiveWorkbook.Path & "\Temp.csv", , , 4 +variants of this do not work(!)
why do they even have the delimiter parameter if it is blocked by the Local parameter ?! this makes no sense at all. but now it works.
This function reads a CSV file of 15MB and copies its content into a sheet in about 3 secs.
What is probably taking a lot of time in your code is the fact that you copy data cell by cell instead of putting the whole content at once.
Option Explicit
Public Sub test()
copyDataFromCsvFileToSheet "C:\temp\test.csv", ",", "Sheet1"
End Sub
Private Sub copyDataFromCsvFileToSheet(parFileName As String, parDelimiter As String, parSheetName As String)
Dim data As Variant
data = getDataFromFile(parFileName, parDelimiter)
If Not isArrayEmpty(data) Then
With Sheets(parSheetName)
.Cells.ClearContents
.Cells(1, 1).Resize(UBound(data, 1), UBound(data, 2)) = data
End With
End If
End Sub
Public Function isArrayEmpty(parArray As Variant) As Boolean
'Returns false if not an array or dynamic array that has not been initialised (ReDim) or has been erased (Erase)
If IsArray(parArray) = False Then isArrayEmpty = True
On Error Resume Next
If UBound(parArray) < LBound(parArray) Then isArrayEmpty = True: Exit Function Else: isArrayEmpty = False
End Function
Private Function getDataFromFile(parFileName As String, parDelimiter As String, Optional parExcludeCharacter As String = "") As Variant
'parFileName is supposed to be a delimited file (csv...)
'parDelimiter is the delimiter, "," for example in a comma delimited file
'Returns an empty array if file is empty or can't be opened
'number of columns based on the line with the largest number of columns, not on the first line
'parExcludeCharacter: sometimes csv files have quotes around strings: "XXX" - if parExcludeCharacter = """" then removes the quotes
Dim locLinesList() As Variant
Dim locData As Variant
Dim i As Long
Dim j As Long
Dim locNumRows As Long
Dim locNumCols As Long
Dim fso As Variant
Dim ts As Variant
Const REDIM_STEP = 10000
Set fso = CreateObject("Scripting.FileSystemObject")
On Error GoTo error_open_file
Set ts = fso.OpenTextFile(parFileName)
On Error GoTo unhandled_error
'Counts the number of lines and the largest number of columns
ReDim locLinesList(1 To 1) As Variant
i = 0
Do While Not ts.AtEndOfStream
If i Mod REDIM_STEP = 0 Then
ReDim Preserve locLinesList(1 To UBound(locLinesList, 1) + REDIM_STEP) As Variant
End If
locLinesList(i + 1) = Split(ts.ReadLine, parDelimiter)
j = UBound(locLinesList(i + 1), 1) 'number of columns
If locNumCols < j Then locNumCols = j
i = i + 1
Loop
ts.Close
locNumRows = i
If locNumRows = 0 Then Exit Function 'Empty file
ReDim locData(1 To locNumRows, 1 To locNumCols + 1) As Variant
'Copies the file into an array
If parExcludeCharacter <> "" Then
For i = 1 To locNumRows
For j = 0 To UBound(locLinesList(i), 1)
If Left(locLinesList(i)(j), 1) = parExcludeCharacter Then
If Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
locLinesList(i)(j) = Mid(locLinesList(i)(j), 2, Len(locLinesList(i)(j)) - 2) 'If locTempArray = "", Mid returns ""
Else
locLinesList(i)(j) = Right(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
End If
ElseIf Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
locLinesList(i)(j) = Left(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
End If
locData(i, j + 1) = locLinesList(i)(j)
Next j
Next i
Else
For i = 1 To locNumRows
For j = 0 To UBound(locLinesList(i), 1)
locData(i, j + 1) = locLinesList(i)(j)
Next j
Next i
End If
getDataFromFile = locData
Exit Function
error_open_file: 'returns empty variant
unhandled_error: 'returns empty variant
End Function
This may help you, also it depends how your CSV file is formated.
Open your excel sheet & go to menu Data > Import External Data > Import Data.
Choose your CSV file.
Original data type: choose Fixed width, then Next.
It will autmaticall delimit your columns. then, you may check the splitted columns in Data preview panel.
Then Finish & see.
Note: you may also go with Delimited as Original data type.
In that case, you need to key-in your delimiting character.
HTH!
Have you tried the import text function.
I have the same issue, I'm not able to open a CSV file in Excel. I've found a solution that worked for me in this question Opening a file in excel via Workbooks.OpenText
That question helped me to figure out a code that works for me. The code looks more or less like this:
Private Sub OpenCSVFile(filename as String)
Dim datasourceFilename As String
Dim currentPath As String
datasourceFilename = "\" & filename & ".csv"
currentPath = ActiveWorkbook.Path
Workbooks.OpenText Filename:=currentPath & datasourceFilename, _
Origin:=xlWindows, _
StartRow:=1, _
DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=False, _
Comma:=True, _
Space:=False, _
Other:=False, _
FieldInfo:=Array(Array(1, 1), Array(2, 1)), _
DecimalSeparator:=".", _
ThousandsSeparator:=",", _
TrailingMinusNumbers:=True
End Sub
At least, it helped me to know about lots of parameters I can use with Workbooks.OpenText method.
Sometimes all the solutions with Workbooks.open is not working no matter how many parameters are set.
For me, the fastest solution was to change the List separator in Region & language settings.
Region window / Additional settings... / List separator.
If csv is not opening in proper way You probly have set ',' as a list separator. Just change it to ';' and everything is solved.
Just the easiest way when "everything is against You" :P
I just solve (my) problem by setting the Local parameter in the Workbook.Open method like this:
xtrct_wb = Workbooks.Open(filePath, Local:=True)
Every information is then in its proper column. Hope it works for you as well.

Resources