How to read whole line from txt file with row delimiter? - ms-access

I have text file with row, which can have several row separators. How to divide this big row into several rows using VBA?.
I need to import this file. I do so (Sep is the field delimiter):
Open FName For Input Access Read As #1
While Not EOF(1)
Line Input #1, WholeLine
If Right(WholeLine, 1) <> Sep Then
WholeLine = WholeLine & Sep
End If
StrArray = Split(WholeLine, Sep)
Wend
or may be you can suggest me another way to import data from txt file with field and row separators?

Well you have a lot of things in your question that need clarification, but maybe this will help you in the right direction. I am going to assume you are appending this to a table.
You'll have to change the following things for your scenario:
1. ImportTableName
2. FieldName
3. FileName
4. sDelimiter - probably this too.
also don't forget to add some error handling. If you drop out without closing the file, it stays locked and will affect your attempts at retrying the import.
Const sDelimiter As String = " sep "
Dim rsImport As ADODB.Recordset
Dim vShortLine As Variant
Dim arrLongLine As Variant
Dim sLongLine As String
Set rsImport = New ADODB.Recordset
With rsImport
.Open ImportTableName, CurrentProject.Connection, adOpenStatic, adLockOptimistic
Open FileName For Input As #1 ' Open file.
While Not EOF(1)
Line Input #1, sLongLine
arrLongLine = Split(sLongLine, sDelimiter)
For Each vShortLine In arrLongLine
.AddNew
!FieldName = vShortLine
Next
Wend
Close #1 ' Close file.
.UpdateBatch
.Close
End With
Set rsImport = Nothing

Related

writing CVS files from application does not put it in proper format - causes issue

So I have a table in SQLSERVEr from where I select data and try to write it to a .CSV file. Everything looks good, but for some reason the first column of data seems to be in some weird kind of format because, I am unable to align text to text or right. When I do click on one of the alignment button, the text in the column barely moves. All other data seems to be fine, I feel like the first column is the only problematic one.
Here's what my code looks like
Dim sSQL As String
Dim cRS As ADODB.Recordset
Dim T As Long
Dim b As Long
Dim strLine As Variant
sSQL = ""
sSQL = "X, Y, Z from tblA”
Set cRS = New Recordset
cRS.Open sSQL, g_cn, adOpenStatic
If cRS.RecordCount > 0 Then
cRS.MoveLast
T = cRS.RecordCount
cRS.MoveFirst
Else
T = 0
End If
Open filenameCSV For Output As #1
For b = 1 To T
strLine = ""
strLine = cRS!X & ","
strLine = strLine & cRS!Y & ","
strLine = strLine & cRS!Z & ","
Print #1, , strLine
cRS.MoveNext
Next
Close #1
cRS.Close
Set cRS = Nothing
So like I said, this code works. It writes data properly to .CSV except with the formatting in the first column, mainly column X
Instead of Print #1, I tried Put #1 but that gives me an error saying Bad File Code
This .csv file is being loaded into some finance software, and i believe the formatting in column X is causing the issues, basically the software does not recognize a value in that column.
FYI..I simpliefied the query.
Anyone have any ideas?
EDIT:
I tried running it from a new file
And I added VBCRLF at the end of the loop before I move to next recordset
strLine = strLine & vbCrLf
Put #1, , strLine
The .csv file gets created but I get a weird symbol in each cell in teh first column
EDIT2 : Opened with Notepad++

create custom text file from Microsoft Access

I'm trying to create a text file from an Access Database that looks exactly like this:
CADWorx P&ID Drop Down List Configuration File.
Notes:
-This file contains information on what
appears in the drop down list in the
CEDIT Additional Data Dialog
-Entries should be separated by a semi-colon (;)
-If a value is not set, an edit box will appear
in the CEDIT Additional Data Dialog instead
of a drop down list.
-Example: AREA_=031;032;033;034A;034B;
Example: SERVICE_=AEC;HW;LH;CCH;
[DOCUMENTATION]
TYPE_=
DATESUB_=
DATEAPR_=
CREATEBY_=
APRBY_=
[LINE]
SERVICE_=OIL;FUEL GAS;
AREA_=
UNIT_=
COUNT_=
TYPE_=
RATING_=
FLGFACE_=
DESIGNPSI_=
DESIGNDEG_=
LINE_NUM_=
OPERPSI_=
OPERDEG_=
SPECPRESS_=
SPECTEMP_=
MINDEG_=
TESTPSI_=
INSULATE_=
HEATTRACE_=
XRAY_=
CODE_=
JOINTEFF_=
WELDPROC_=
INSPECT_=
MATPIPE_=
COMPNOTE_=
NOTE_=
USER1_=
All the fields on the left (that end with '_=') are field titles in my database.Then as explained above, values for those fields must be added and separated by a semicolon. I've been researching for over a week and pretty much just hitting dead ends with text file customization in Access. Can someone tell me if this is the way to go? Or should I export the data to Excel and create the text file from there?
Your help is very much appreciated. Thanks in advance.
Here's the basics to write records to a file:
Dim dbs As Database
Dim rst As Recordset
Dim intFileDesc As Integer 'File descriptor for output file (number used by OS)
Dim strOutput As String 'Output string for entry
Dim strRecordSource As String 'Source for recordset, can be SQL, table, or saved query
Dim strOutfile As String 'Full path to output file
Kill strOutfile 'Delete the output file before using it.
'Not necessary, but ensures you have a clean copy every time
intFileDesc = FreeFile 'Get a free file descriptor
Open strOutfile For Binary As #intFileDesc 'Open the output file for writing
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset(strRecordSource ) 'open the recordset based on our source string
With rst 'make things easier for ourselves
While Not .EOF
strOutput = !Field1 & ";" & !Field2 & ";" & !Field3
Print #intFileDesc, strOutput 'Print output string to file
.MoveNext 'Advance to next record in recordset
Wend
.Close 'Close this recordset
End With
Close #intFileDesc 'Close output file
Set rst = Nothing
Set dbs = Nothing 'Garbage handling before we exit the function
The essential line is this:
Print #intFileDesc, strOutput 'Print output string to file
by which you can write one line at a time.
Thus, build a function that expands on this, creating your output line by line (including empty lines for spacing) until done. That's it.
It takes a lot of code but really is quite trivial. And there is no other way for outputs like these.

SQL Query is updated when user updates Excel

I have an excel document that I want to link to an SQL query. In the excel document I have a list of item numbers. Whenever an item number gets changed I want the sql query to query that list of item numbers and return an output. Basically I want the excel sheet to use the Item Number as a parameter for the database item numbers ? The excel item numbers are updated daily.
Keep in mind that this is a mock example for what you are trying to do. With no knowledge of your database or spreadsheet, I can't guarantee that any of this will even work. At the very least, it will require you to make some adjustments before you can use it.
With that in mind, I have commented on various parts of the code to let you know what is going on there. The sections that have a *** are areas that you may want to change. The sections with ### are areas that you will HAVE to change for it to work for you.
This code assumes that you have a list of item numbers in column A of sheet 1, that each item number will only return one record, and that there are no blank cells in your list of item numbers.
Sub GrabItemInfo()
Dim objADO As New ADODB.Connection
Dim objRecSet As New ADODB.Recordset
Dim objCmd As New ADODB.Command
Dim strConn As String
Dim strSQL As String
Dim RowNum As Long
Dim errNum As Long
'open a connection to the database
'### change the properties for the connection to suit your needs
strConn = "DSN=DSNName; DBQ=Database; UID=Username; PWD=Password"
objADO.Open strConn
objCmd.ActiveConnection = objADO
objCmd.CommandType = adCmdText
'errNum is the row that the error log will start on
'***change errNum to change which row it starts on
errNum = 1
'***changeRowNum here to change which row to start on
RowNum = 1
'start the loop
Do Until ThisWorkbook.Sheets(1).Cells(RowNum, 1) = ""
On Error Resume Next
'### change the sql to whatever you need
'*** change the cells section if you're not using the first column
strSQL = "SELECT [field] FROM [table] WHERE ItemNum = " & ThisWorkbook.Sheets(1).Cells(RowNum, 1).Value
objCmd.CommandText = strSQL
Set objRecSet = objCmd.Execute
'pastes results from query into the cell next to the item number
'***change the cells section if you want to use a different column
ThisWorkbook.Sheets(1).Cells(RowNum, 2).CopyFromRecordset objRecSet
'clear out the recordset before the loops starts again
Set objRecSet = Nothing
'put the item number, error number, and error description on the second sheet of the work book
'***change the sheet number to put it on another sheet if you're already using the second
If Err > 0 Then
ThisWorkbook.Sheets(2).Cells(errNum, 1).Value = ThisWorkbook.Sheets(1).Cells(RowNum, 1).Value
ThisWorkbook.Sheets(2).Cells(errNum, 2).Value = Err.Number
ThisWorkbook.Sheets(2).Cells(errNum, 3).Value = Err.Description
On Error GoTo 0
End If
'raise the value for the row for the next iteration
RowNum = RowNum + 1
Loop
'clear out the connection
Set objADO = Nothing
Set objRecSet = Nothing
Set objCmd = Nothing
End Sub
For more information on connection strings, I recommend http://www.connectionstrings.com
It's a great resource to use for figuring out what kind of connection string you need. Connections strings can be...tricky...sometimes, and this really helps.
If you need any resources for SQL, I would recommend http://www.w3schools.com/sql
They have a good introduction to it there. Past that, get a good reference book, find a mentor, join forums(or Q&A sites like this one), etc. If you look into the SQL tag on this site, there is more information, along with some recommended resources as well.
Good luck.

How to Modify/Update a .CSV file through VB 6.0

I have a .CSV File with 5 values in a row , i want to modify the file in a way i should add one more value in the Beginning/End/Middle of the row.
How to add a new row with a set of values in the .CSV File?
How to do this in a simple way?
There is no magic way to insert things into the middle of a stream file (such as any text file including CSV files).
So this means you need to read the old file and modify it as you go writing a new file out.
There are many ways to do this though:
Read the input file into memory as a blob and work on it there then write out the modified data.
Read/write it with changes line by line.
Use Jet Text IISAM, Log Parser's COM API, etc. which allow SQL and SQL-like operations on text data in tabular formats such as CSV.
The simplest and most general way is line by line read/modify/write. This can be slower than the "blob" approach for small to middling files but doesn't risk the headaches that may result when a large file must be processed.
For very large files this can be optimized by reading, parsing, modifying, then writing in "chunks" to minimize I/O costs. But this can also be more complex to program correctly.
This piece of code may help , this is not an answer but it will help
Dim line As String
Dim arrayOfElements() As String
Dim linenumber As Integer
Dim i As Integer
Dim opLine As String
Dim fso As New FileSystemObject
Dim ts As TextStream
line = ""
Open strPath 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, "|")
If Not linenumber = 1 Then
If UBound(arrayOfElements) = 2 Then
line = line & "|x|y"
opLine = opLine & line & vbCrLf
End If
Else
line = line & "|col4|col5"
opLine = opLine & line & vbCrLf
End If
Loop
Close #1 ' Close file.
Set ts = fso.CreateTextFile(strPath, True)
ts.WriteLine (opLine)
ts.Close
fso need to be closed!
Set fso = Nothing

How to write to a specific line in a text file using vb

I have a text file with this sample data
abduct test|1
chip test|2
hatter test|3
evil test|4
I would like to know how I could loop through it to find a user and remove that line.
This is what I have so far:
Public Sub RemoveMember(member As String)
Dim u As String, strdata() As String
Open (App.Path & "\Membership.txt") For input As #1
Do
input #1, u
strdata = Split(u, "|")
If strdata(0) = member Then
'figure out a way to remove this line from the text file'
End If
Loop Until EOF(1)
Close #1
End Sub
I would say:
Read in the lines one by one
Check if the line contains the member to be deleted
Write back the line to a new file if it does not
After reading all the lines delete the original file
Rename the new file to the original file
Stefan's method is probably faster but will use a lot of memory if the file grows very large.
I am not familiar wityh VB's native file method. Using FileSystemObject (reference Microsoft Scripting Host) you wil get:
Dim clsOriginalFile as TextStream
Dim clsNewFile as TextStream
Dim FSO as New FileSystemObject
Dim varLine as Variant
Dim strLine as String
set clsOriginalFile=FSO.OpenTextFile "members.txt", ForReading
set clsNewFile =FSO.OpentTextFile "temp.txt", ForWriting, True
Do While Not clsOriginalFile.AtEndOfStream
varLine = clsOriginalFile.ReadLine
strLine=varLine
If instr(strLine,member)=0 Then
clsNewFile.WriteLine strLine
End If
Loop
clsOriginalFile.Close
clsNewFile.Close
FSO.DeleteFile("members.txt")
FSO.MoveFile("temp.txt","members.txt")
Written without the help of the IDE, so there may a few typos in the code.