Reputation: 704
I am trying to query a text file, a csv file and return the result of a query to a text file. I tried this apporoach https://stackoverflow.com/a/581638/3480717 which looked very promising, returning data direct from SQL command to a file, skipping the creation of a recordset. Prompting as it may be, I cannot make it work, here is my version:
Sub test()
Dim db: db = "C:\Databases\"
Dim exportFile: exportFile = "C:\Databases1\Exp.txt"
Dim cn: Set cn = CreateObject("ADODB.Connection")
cn.Open _
"Provider = Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & db & ";" & _
"Extended Properties=""text;HDR=YES;FMT=Delimited(,)"""
cn.Execute "SELECT [Surname INTO [text;HDR=Yes;Database=" & exportDirFile & _
";CharacterSet=65001] FROM PhoneList.csv"
cn.Close
End Sub
PhoneList.csv - My data is a three column file with Surname, Name and PhoneNumber. For a test I tried to extract PhoneNumber column.
The code stops on cn.Execute
I get an error saying that "Cannot update. Database or object is read-only.
What am I doing (very) wrong? I have access to the files/can open and save them. It seems that the problem lies somewhere else.
How it would look like in VBS? (the code does not need Excel to visualise anything).
Thx very much for comments.
Upvotes: 0
Views: 1476
Reputation: 704
I succeeded with the following (both in VBA and VBS):
Dim db: db = "C:\Users\jkotows2\Desktop\sql_script\"
Dim cn: Set cn = CreateObject("ADODB.Connection")
cn.Open _ "Provider=Microsoft.ACE.OLEDB.15.0;" & _ "Data Source=" & db & ";" & _ "Extended Properties=""text;HDR=YES;FMT=Delimited(;)"""
cn.Execute "INSERT INTO [exp.csv] SELECT [Surname],[Name],[No] FROM [PhoneList.csv]"
cn.Close
Upvotes: 0
Reputation: 38755
Your
cn.Execute "SELECT [Surname INTO [text;HDR=Yes;Database=" & exportDirFile & _
";CharacterSet=65001] FROM PhoneList.csv"
should be
cn.Execute "SELECT [Surname] INTO [text;HDR=Yes;Database=" & "C:\Databases1" & _
";CharacterSet=65001] [Exp.txt] FROM PhoneList.csv"
(For TEXT, Database is a folder and the target of INTO a File name)
Upvotes: 2