Remove Double Quotes While Reading CSV Files in VBA - vba

In VBA, I need to import a few R generated CSV files. However, the split function did not work properly and gaveType mismatch. My best guess is that: VBA added double quotes between each imported line. So the first line becomes " 47.27284, 130.5583, 44.826609, 189.905367". I tried to remove double quotes using replace or remove the first and last character but the error still existed. Any suggestions to deal with this issue?
CSV file
dose_BMD_r, dose_ED_r, dose_BMD_c, dose_ED_c
47.27284, 130.5583, 44.826609, 189.905367
47.27284, 130.5583, 52.226171, 233.338840
47.27284, 130.5583, 8.484266, 6.887616
VBA code
lin_ind = 1
Open text_fn For Input As #1
Do Until EOF(1)
Line Input #1, textline
If lin_ind = 1 Then
'Do nothing
Else
textline_1 = Split(textline, ",")
End If
lin_ind = lin_ind + 1
Loop
Close #1

Split function returns array. So the variable where you store Split's return value, should be array/variant.
Declare it as Dim textline_1 that's it. It will work.
OR Dim textline_1 () As String

Related

Gettint text from lastline in richtextbox

I want to copy the last line of a rich textbox.
I am avoiding Dim lastLine As String = RichTextBox1.Lines(RichTextBox1.Lines.Length - 1)as
it's not working properly, as It works just if there are atleast 2 lines in it.
I'm trying with MsgBox(RichTextBox1.Lines(UBound(richtextbox1.Lines))) but the problem is that even if the richtextbox has just 1 line of text but the cursor is in the second empty line, it will give back "" as I think the software is reading the empty 2nd line.
There is a solution to that?
Thanks
This will get the last non-empty line:
RichTextBox1.Lines.Where(Function(line) line <> String.Empty).Last()
There are some potential issues with that. If there's no text at all or if there are multiple lines but they are all empty, that will throw an exception. To allow for that, you can call LastOrDefault instead, in which case it would return Nothing.
If you only want to exclude the last empty line, e.g. if you have some text followed by a line break and then another line break then you want to get the first of those two empty lines, then you can't really do it in one line:
Dim lines = RichTextBox1.Lines
Dim upperBound = lines.GetUpperBound(0)
Dim lastLine = lines(upperBound)
If lastLine = String.Empty Then
If upperBound > 0 Then
lastLine = lines(upperBound - 1)
Else
lastLine = Nothing
End If
End If
'Use lastLine here.

VB.NET - Replace column value in text file that is space delimited

I am trying to run a vb.net script from SSIS to perform the following in a space delimited text;
Loop through all files in directory (I've already coded this using .GetFiles)
Within each text file loop through each line within the file
Replace/Insert a value in the line
Save the file
I'm struggling to come up with a method to replace/insert a value. I do not believe this is possible with ReadLines and my searches haven't turned up any solutions for my situation. All of the solutions I'm finding recommend using .split, but since this file is text delimited and column sizes vary, .split and .replace will not work.
Any ideas? Here is an example of a line from the text file and where I want to insert the value;
WMS0104 N00011 800171548-1 20190221 OVPRC <INSERT VALUE HERE> PRINTER13 000000000000000000000000000000010000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000 2019022108511300 00000000000000 00000000000000001
Got it
Dim BeforeWH_ID, ExistingWH_ID, AfterWH_ID, DesiredWH_ID, NewLineRecord As String
DesiredWH_ID = "034 "
Dim lines() As String = IO.File.ReadAllLines(ExportFilePath)
'Loop through each line in the array
For i As Integer = 0 To lines.Length - 1
'Fill line variables
BeforeWH_ID = Mid(lines(i), 1, 215)
ExistingWH_ID = Mid(lines(i), 215, 32)
AfterWH_ID = Mid(lines(i), 247, 377)
NewLineRecord = BeforeWH_ID & DesiredWH_ID & AfterWH_ID
'Compare WH_ID
If ExistingWH_ID <> DesiredWH_ID Then
'Replace the line in the array
lines(i) = NewLineRecord
Else
'Keep the line in the array
lines(i) = lines(i)
End If
'Reset Variables
BeforeWH_ID = Nothing
ExistingWH_ID = Nothing
AfterWH_ID = Nothing
NewLineRecord = Nothing
Next
'Overrite existing file with line array
IO.File.WriteAllLines(ExportFilePath, lines)

Removing CR/LF at end of file in VB.net

I've searched for a solution to this, but any I've found are either doing much more than I need or are not exactly what I want.
I have files I want to append to. I need to append to the end of the last line but they all have a carriage return and so I'll end up appending to the new line if I just append as normal.
All I want is to make a subroutine that takes a file path and removes the CR/LF at the end of it, no more, no less. Any help pointing me at a solution to this would be appreciated. I'm surprised there isn't a built in function to do this.
Dim crString = Environment.NewLine '= vbCrLf
Dim crBytes = Encoding.UTF8.GetBytes(crString)
Dim bytesRead(crBytes.Length - 1) as Byte
Dim iOffset As Integer = 0
Dim stringRead As String
Using fs = File.Open("G:\test.txt", FileMode.Open, FileAccess.ReadWrite)
While iOffset < fs.Length
fs.Seek(- (crBytes.Length + iOffset), SeekOrigin.End)
fs.Read(bytesRead,0, crBytes.Length)
stringRead = Encoding.UTF8.GetString(bytesRead)
If stringRead = crString Then
fs.SetLength(fs.Length - (crBytes.Length * iOffset + 1))
Exit While
End If
iOffset += 1
End While
End Using
I open the text file as FileStream and set its position to the end of the file - length of the carriage return string.
I then read the current bytes while decreasing the offset until I found a carriage return or the eof has been reached.
If a CR has been found I remove it and everything what comes after.
If you don´t want that just remove the loop and check the eof only.
But there could be some vbNullString at the eof that´s why I´m using the loop.
Please note that I used UTF8 encoding in my example. If you have other encodings you have to adapt it accordingly.
test.txt before run:
test.txt after code snippet run:
EDIT: fs.SetLength part was wrong in case of last character in file was not a CR.
I have found String.Replace(ControlChars.CrLf.ToCharArray(),"") works.
Probably better ways to do it as well!

Reading csv file with strange line deliminter in VBA

I have a input file which I am struggling to read in line by line, The file can be found here and is also shown below:
I would like to add the first value as key and the third value as item in a dictonary
Then later I can do this: a = myDictonary("CREATED_BY") and this will then return "Eigil..." (Order and number of lines my vary from time to time..)
But somehow I can not get the split to work:
Dim hf As Integer: hf = FreeFile
Dim lines() As String, i As Long
Open FileName For Input As #hf
Line Input #hf, dataLine
lines = Split(dataLine, vbNewLine)
lines = Split(dataLine, "\n")
lines = Split(dataLine, "CR")
lines = Split(dataLine, "LF")
Close #hf
I also tried to follow this thread
For people who like to use dictinary here is my code for that:
Set getProjectDictionary = CreateObject("Scripting.Dictionary")
Dim item As String
Dim key As String
Dim dataLine As String
Open FileName For Input As 1
While Not EOF(1)
On Error Resume Next
Line Input #1, dataLine
temp = Split(dataLine, ",")
If Not temp(0) = "" Then
getProjectDictionary.Add temp(0), temp(3)
End If
Wend
Close 1
I added some debug output below:
The screenshot you attached shows that the file uses CR LF as linebreaks but the file I downloaded from your Google Drive link actually uses LF only, so you might want to use:
lines = Split(dataLine, vbLf)
Also, the file uses Little Endian UCS-2 encoding with BOM. If you simply open the file using the Open statement, you are likely to run into corrupt characters and other encoding related problems. I would suggest using Filesystem object instead.
I think this has the answer - split on vbcrlf?
CRLF in VBScript
Of the 4 examples you gave, "CR" and "LF" would look for the literal strings "CR" and "LF", which is not what you want. VB doesn't recognize "\n" like most C-like languages, so that's out. vbnewline was the closest to working, but I think this might help you:
http://www.jaypm.com/2012/08/the-difference-between-vbcrlf-vbnewline-and-environment-newline/
Here is my code that currently seems to work well:
Option Explicit
Sub test()
Dim a As Object
Set a = getPropertiesDictionary("c:\Temp\Creo\param_table.csv")
Debug.Print a.item("PTC_WM_CREATED_BY")
End Sub
' populate dictinoary with document types based on input file
Function getPropertiesDictionary(FileName As String) As Object
Set getPropertiesDictionary = CreateObject("Scripting.Dictionary")
Dim temp() As String
Dim dataLine As String
Dim hf As Integer: hf = FreeFile
Dim lines() As String, i As Long
Open FileName For Input As #hf
Line Input #hf, dataLine
lines = Split(dataLine, vbLf)
Close #hf
For i = 0 To UBound(lines) - 1
temp = Split(lines(i), ",")
If Not temp(0) = "" Then
getPropertiesDictionary.Add temp(0), temp(2)
End If
Next
End Function

IndexOf Method VB.net

How do I use the Indexof Method to search for an Index a number? The number will be different on each line of the file. Each array has a name and a different zip code. I want to tell it to search for the first number in the line. Everything before that index will be first name, last name, and then zip code.
infile = IO.File.OpenText("Names.txt")
'process the loop instruct until end of file
intSubscript = 0
Do Until infile.Peek = -1
'read a line
strLine(intSubscript) = infile.ReadLine
intSubscript = intSubscript + 1
Loop
infile.Close()
A solution from how I understand this:
Instead of using the IndexOf, you can save each part of the file on a different line (ReadLine).
If you really need the IndexOf: It's just String.IndexOf(EnterCharacterHere)
You could also read this file and only use the numbers found:
First you make a const string const cstrNumbers as string = "0123456789" and then do the following:
For x as integer = 0 to strInput -1
strTemporary = strInput.Substring(x,1)
If InStr(cstrNumbers, strTemporary) <> 0 Then
strOutput &= strTemporary
strOutput will contain the numbers then.
Hope this helps,
Simon
EDIT:
This would be easier with a database, but I have no experience with db in vb.net.
You could do a substring combined with the InStr I mentioned.
First you need a function that will return the first occurrence of a number. (With InStr)
And then use this in the substring (String.SubString(FirstOccurence, LengthOfZip)
Don't have the time to do the complete code now..Hope this helps you a bit