Append data to beginning of CSV file - vba

I'm working on an Access application and I've run into the following snag. Currently I'm writing an output file by exporting a query as a CSV file, however this file needs to be read by an older database system and will need a header row containing some identifying data.
I can construct the string for this header row in VBA without any trouble, but I'm not quite sure how to insert it in the first line of the CSV file, rather than it being appended at the end. How can I do this/achieve the desired result?

Open the file, read it, write the header, write back the data:
Dim data As String
Dim hF As Integer: hF = FreeFile()
Open "c:\path\foo.csv" For Input As #hF
data = Input$(LOF(hF), #hF)
Close #hF
Open "c:\path\foo.csv" For Output As #hF
Print #hF, "Header data here" & vbCrLf & data
Close #hF

Consider explicitly labeling your query columns with the corresponding header column as aliases. Then, export to csv with these headers using the VBA method, TransferText:
SQL
SELECT Col1 As Header1,
Col2 As Header2,
Col3 As Header3,
Col4 As Header4
...
FROM Table1
INNER JOIN Table2
ON Table1.PKID = Table2.FKID
VBA
Dim csvpath As String
csvpath = "C:\Path\To\CSVFile.csv"
DoCmd.TransferText acExportDelim, , "QueryName", csvpath, True

Related

How to populate column based on other columns

I need to understand why this does not work in MS Access:
UPDATE main_records
SET main_records.rece = Str(main_records.Nr) & "," & Str(main_records.Pag);
The intent is to populate the rece column (63 chars string) in all records of main_records with the contents of Nr and Pag (converted to string and concatenated).
It looks so easy but ...
"the contents of Nr and Pag (converted to string and concatenated)"
If that is what you intend to do, you are to use a string conversion function
examples is
CStr( expression ).

Importing Data from Excel file to MSAccess formatting each column in VBA

I'm coding a system which import a excel file to a ms access database, but I would like to know if is possible format every column before import to the database.
For example:
EXCEL FILE (xls or xlsx): COLUMN A = DateTime; COLUMN B = Integer; COLUMN C = Char(25); COLUMN D = VARCHAR(255)...
I'm using this code right now but it's automatically.
Do While Len(strFile) > 0
strPathFile = strPath & strFile
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
strTable, strPathFile, blnHasFieldNames
strFile = Dir()
Loop
Yes it is possible and advisable to format the columns in excel before importing, so as to reduce risk of some data not been correctly imported.
Select the cells(s) you want to modify.
Click the drop-down arrow next to the Number Format command on the Home tab. The Number Formatting drop-down menu will appear.
Select the desired formatting option
formatting options in excel includes
A.ABC General
B. Number
C Currency
D Short date
E Long date
and some others.
You have to format the columns in excel manually, it can not be programmatically done from access

How to use select query from csv file with second row as header (ADODB connection).Need to skip first row

Connection String
Dim Db = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & SourcePath & ";Extended Properties=""Text;HDR=Yes;FMT=Delimited;"";"
the Header is start from 2nd row, how to exclude 1st row while using Select query from CSV file. Please help to amend the connection string to start from second row
Sample Query.....
Select [Col1], Col1/Col2 as [Average] From [CSV File] Where Col3 > 0
In order to get your rows by a file .csv you can use this method as an alternative which gives you a list of rows that contains an array by columns.
Replace the separator char with the separator that is used in your file CSV also the path of your CSV file
Dim separator As Char = CChar(";")
Dim linesWithoutHeader As List(Of String()) = (From line In IO.File.ReadAllLines("C:\yourPathCsvFile.csv")
Select row = line.Split(separator)
Skip 1).ToList

export SQL data to a csv file from ASP.net

I have a view in the database, i would like to call that view and export the data to a Csv file. I have used the following link to come up with a solution however my view returns a few columns which has values with commas so while opening the csv i get the error the csv is unsafe, might by a sylk file etc. Once i open it there is no date in the CSV.
The link i used
https://www.aspsnippets.com/Articles/Export-data-from-SQL-Server-to-CSV-file-in-ASPNet-using-C-and-VBNet.aspx
I am using VS 2017
SQL and
VB.Net
Thanks in advance
That code is a bit dodgy actually, because it is explicitly replacing commas in data with semicolons and it is also adding an extra comma to the end of each line. Here's concise way to generate CSV data from a DataTable with quoted field values:
Dim csv = String.Join(Environment.NewLine,
myDataTable.AsEnumerable().
Select(Function(row) """" &
String.Join(""",""",
row.ItemArray) &
""""))
If you're not au fait with LINQ, here's a more conventional way to do the same thing:
Dim csv As String
For rowIndex = 0 To myDataTable.Rows.Count - 1
'Add a line break before all but the first line.
If rowIndex > 0 Then
csv &= Environment.NewLine
End If
Dim row = myDataTable.Rows(rowIndex)
'Add a double-quote before the first field value.
csv &= """"
For columnIndex = 0 To myDataTable.Columns.Count - 1
'Add a closing double-quote, a delimiting comma and an opening
' Double-quote before all but the first field value.
If columnIndex > 0 Then
csv &= ""","""
End If
csv &= row(columnIndex).ToString()
Next
'Add a double-quote after the last field value.
csv &= """"
Next

Taking record from Excel and searching multiple records in .csv/.txt file using vba [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am looping through Excel (for example record city ="Paris") and then want to retrieve multiple records from .csv files (there could be possibility of retrieving multiple records available in .csv files pertaining to city paris)
Here is be basic structure of .txt which tab delimited file.
1 Tokyo JA test Tokyo "test, testttttttttt." "images url to download delimited by ,"
2 Tokyo JA test Tokyo "test, testttttttttt." "images url to download delimited by ,"
3 Paris FR test Tokyo "test, testttttttttt." "images url to download delimited by ,"
Can anybody help me with this, please note that above file is .txt file and having said that I want to know how many records are ( count ) met with per Excel records in the .txt/csv file so I want to do other activities required in my system.
Here is my code :
currPath1 = "C:\sourceexcel.xlsx"
currentPath2 = "C:\CSVtoberead.txt"
fileNum =FreeFile()
Open currentPath2 For Input As fileNum
totoalRows= xlsheet.UsedRange.Rows.Count
startrow1 =1
PreviousCity=""
For x= startRow To totoalRows
currentCity = xlsheet.Cells(startRow,3 ).value '' this is city from excel sheet
Do While Not EOF( fileNum )
Line Input #fileNum, txt '''file to read .txt file
parseRecord = Split (txt,Chr(9))
If parserecord(1)= currentCity Then
Reading the text file repeatedly, once for every occurrence of a city in your worksheet, is quite inefficient. Instead, you could read the file just once, loading the data in each line into a dictionary which is keyed by the cities and whose values are collections of arrays (each array corresponding to a split of a line). Something like this:
Function ExtractData(fname As String, colNumber As Long, Optional delim As String = vbTab) As Variant
'Takes a delimited txt file and returns a dictionary
'keyed by the entries in the specified column
'the values for a key is a collection of split lines
Dim fileNum As Long
Dim txt As String
Dim C As Collection
Dim d As Variant, k As Variant, parseRecord As Variant
Set d = CreateObject("Scripting.Dictionary")
fileNum = FreeFile()
Open fname For Input As fileNum
Do While Not EOF(fileNum)
Line Input #fileNum, txt '''file to read .txt file
parseRecord = Split(txt, delim)
k = parseRecord(colNumber)
If d.exists(k) Then
d(k).Add parseRecord
Else
Set C = New Collection
C.Add parseRecord
d.Add k, C
End If
Loop
Close #fileNum
Set ExtractData = d
End Function
You should be able to use the above function to streamline your code. To give you some idea of how it works, I copied your data (with the spaces replaced by tabs) into a text file and ran:
Sub test()
Dim v As Variant
Set v = ExtractData("C:/Programs/test.txt", 1)
Debug.Print v("Tokyo").Count
Debug.Print v("Paris").Count
Debug.Print Join(v("Tokyo")(2), "/")
End Sub
The output is:
2
1
2/Tokyo/JA/test/Tokyo/"test, testttttttttt."/"images url to download delimited by ,"
Expanding a bit: run the function just once, at the beginning of your code, and assign it to a variable (e.g. v). Then iterate through the column of the spreadsheet which contains the cities. For each city, v.Exists(city) can check if the city occurs in the data. If it does, then v(city).Count will tell you how many times, and things like v(city)(i) can be used to access the individual lines of data that correspond to that city. If j is a specific column number then v(city)(i)(j) will give (as a string) the data in column j of occurrence i of the given city.