exporting a query output to a text file - ms-access

I have an access query which I am trying to export to a text file using the following code:
DoCmd.TransferText acExportFixed, "Export Specification", _
"Test Query", "C:\Users\Documents\TestOutput.txt", True
The issue I am having is: The output file "TestOutput.txt" has the data displayed with fixed width but the column headers are comma delimited. I want the column headers to be fixed width too.
What would column headers not be displayed same as the rest of the data?

AFAICT, that is an unavoidable "feature" of TransferText. It seems to lack any kind of built-in intelligence to say "OK, we're exporting as acExportFixed, so let's examine the column widths defined in Export Specification and output the column headers using those same widths". Instead it just gives the column names as a comma-separated list.
As with everything else in Access, when its default behaviors are unsatisfactory, you can write VBA code to do it your way.
Const VB_FORREADING = 1
Const VB_FORWRITING = 2
Const cstrFile As String = "C:\Users\Documents\TestOutput.txt"
Const cstrHeaderRow As String = "col1 col2 etc..."
Dim oFSO As Object
Dim oFile As Object
Dim strContents As String
' do TransferText without the field names '
' (HasFieldNames default = False) '
DoCmd.TransferText acExportFixed, "Export Specification", _
"Test Query", cstrFile
Set oFSO = CreateObject("Scripting.FileSystemObject")
' read file content into strContents string variable '
Set oFile = oFSO.OpenTextFile(cstrFile, VB_FORREADING)
strContents = oFile.ReadAll
oFile.Close
' re-write file using cstrHeaderRow plus strContents '
Set oFile = oFSO.OpenTextFile(cstrFile, VB_FORWRITING)
oFile.write cstrHeaderRow & vbCrLf & strContents
oFile.Close
Set oFile = Nothing
Set oFSO = Nothing

Related

Read a CSV File Delimited with Hash

I have a CSV export from an LDAP DB and I have to read data with a Classic ASP page.
The format of the CSV file is like
CRDLVR47E67L781V#1653#CORDIOLI#ELVIRA#658#elvira.cordioli#sender.at#SI
I can read the file line by line, and have to split the line manually.
If I change the # value to a comma I can access the file by column. Can I make the asp page able to access the file by column, in order to obtain the single value keeping the # separator?
My connection string is
Set oConn = Server.CreateObject("ADODB.connection")
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=http://export/caselle.csv;Extended Properties='text;HDR=Yes;FMT=Delimited'"
and I can read line from the CSV file with the query
Set RS=Server.CreateObject("ADODB.recordset")
RS.open "SELECT * FROM utenti_aospbo.csv", oConn
now I can only read rs.fields(0), that output the entire line, like
CRDLVR47E67L781V#1653#CORDIOLI#ELVIRA#658#elvira.cordioli#sender.at#SI
I'd like to have
response.write rs.fields(0) 'CRDLVR47E67L781V
response.write rs.fields(5) 'elvira.cordioli#sender.at
While I can't rule out that there is some version of OLEDB that does HTTP or accepts FMT and FORMAT in the connection string, I'm sure that the Data Source property of an ADODB Text connection needs to be a folder.
Instead of trying to specify a global separator in the connection string or the in the registry, I'd use a schema.ini file to describe the meta info in a file specific way.
All in one:
cscript 41224005.vbs
.\41224005.vbs
Option Explicit
Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")
Dim sF
For Each sF In Split(".\41224005.vbs ..\data\schema.ini ..\data\data1.txt")
WScript.Echo sF
WScript.Echo oFS.OpenTextFile(sF).ReadAll()
WScript.Echo "---------------"
Next
Dim sDir : sDir = oFS.GetAbsolutePathName("..\data\")
Dim sCS : sCS = Join(Array( _
"Provider=Microsoft.Jet.OLEDB.4.0" _
, "Data Source=" & sDir _
, "Extended Properties='" & Join(Array( _
"text" _
), ";") & "'" _
), ";")
Dim oDb : Set oDb = CreateObject("ADODB.Connection")
oDb.Open sCS
'WScript.Echo oDb.ConnectionString
Dim oRS : Set oRS = oDb.Execute("SELECT * FROM [data1.txt]")
WScript.Echo oRS.Fields(0).Value
WScript.Echo oRS.Fields(6).Value
oRS.Close
oDb.Close
---------------
..\data\schema.ini
[data1.txt]
FORMAT=Delimited(#)
ColNameHeader=False
---------------
..\data\data1.txt
CRDLVR47E67L781V#1653#CORDIOLI#ELVIRA#658#elvira.cordioli#sender.at#SI
---------------
CRDLVR47E67L781V
SI

Export all tables to txt files with export specification

I have a Access DB containing several different tables, each with a different structure (number & names of fields, number of rows, title).
What I would like to do is to export all these tables into txt files, with a given separator ("|"), point as decimal separator, quotes for strings.
I have browsed the internet and what I got was:
use DoCmd.TransferText acExportDelim command
save a customized export specification and apply it
I get an error messagge ("object does not exist") and I think it is related to the fact that the export specification is "sheet-specific", i.e. does not apply to tables with different fields and fieldnames.
Can you help me?
thanks!!
EDIT.
I post also the original code I run. As I said before, I am new to VBA, so I just looked for a code on the web, adapted it to my needs, and run.
Public Sub ExportDatabaseObjects()
On Error GoTo Err_ExportDatabaseObjects
Dim db As Database
Dim db As DAO.Database
Dim td As TableDef
Dim sExportLocation As String
Dim a As Long
Set db = CurrentDb()
sExportLocation = "C:\" 'Do not forget the closing back slash! ie: C:\Temp\
For a = 0 To db.TableDefs.Count - 1
If Not (db.TableDefs(a).Name Like "MSys*") Then
DoCmd.TransferText acExportDelim, "Export_specs", db.TableDefs(a).Name, sExportLocation & db.TableDefs(a).Name & ".txt", True
End If
Next a
Set db = Nothing
MsgBox "All database objects have been exported as a text file to " & sExportLocation, vbInformation
Exit_ExportDatabaseObjects:
Exit Sub
Err_ExportDatabaseObjects:
MsgBox Err.Number & " - " & Err.Description
Resume Exit_ExportDatabaseObjects
End Sub
Before running the code, I manually exported the first table saving the Export_specs to a file.
Consider a db with two tables, A and B.
When I run the code A is properly exported, then I get the following errore message "3011 - The Microsoft Access database engine could not find the object 'B#txt'. Make sure the object exists and that you spell its name and the path name correctly. If 'B#txt' is not a local object, check your network connection or contact the server administration".
So, it's kind of complex. I've created a routine that imports files using ImportExport Specs, you should be able to easily adapt to your purpose. The basic operation is to create a spec that does exactly what you want to one file. Then, export this spec using this code:
Public Function SaveSpecAsXMltoTempDirectory(sSpecName As String)
Dim oFSO As FileSystemObject
Dim oTS As TextStream
Set oFSO = New FileSystemObject
Set oTS = oFSO.CreateTextFile("C:\Temp\" & sSpecName & ".xml", True)
oTS.Write CurrentProject.ImportExportSpecifications(sSpecName).XML
oTS.Close
Set oTS = Nothing
Set oFSO = Nothing
End Function
Then open this file in Notepad and replace the file name with some placeholder (I used "FILE_PATH_AND_NAME" in this sample). Then, import back into database using this code:
Public Function SaveSpecFromXMLinTempDirectory(sSpecName As String)
Dim oFSO As FileSystemObject
Dim oTS As TextStream
Dim sSpecXML As String
Dim oSpec As ImportExportSpecification
Set oFSO = New FileSystemObject
Set oTS = oFSO.OpenTextFile("C:\Temp\" & sSpecName & ".xml", ForReading)
sSpecXML = oTS.ReadAll
For Each oSpec In CurrentProject.ImportExportSpecifications
If oSpec.Name = sSpecName Then oSpec.Delete
Next oSpec
Set oSpec = CurrentProject.ImportExportSpecifications.Add(sSpecName, sSpecXML)
Set oSpec = Nothing
oTS.Close
Set oTS = Nothing
Set oFSO = Nothing
End Function
Now you can cycle thru the files and replace the placeholder in the spec with the filename then execute it using this code:
Public Function ImportFileUsingSpecification(sSpecName As String, sFile As String) As Boolean
Dim oSpec As ImportExportSpecification
Dim sSpecXML As String
Dim bReturn As Boolean
'initialize return variable as bad until function completes
bReturn = False
'export data using saved Spec
' first make sure no temp spec left by accident
For Each oSpec In CurrentProject.ImportExportSpecifications
If oSpec.Name = "Temp" Then oSpec.Delete
Next oSpec
sSpecXML = CurrentProject.ImportExportSpecifications(sSpecName).XML
If Not Len(sSpecXML) = 0 Then
sSpecXML = Replace(sSpecXML, "FILE_PATH_AND_NAME", sFile)
'now create temp spec to use, get template text and replace file path and name
Set oSpec = CurrentProject.ImportExportSpecifications.Add("Temp", sSpecXML)
oSpec.Execute
bReturn = True
Else
MsgBox "Could not locate correct specification to import that file!", vbCritical, "NOTIFY ADMIN"
GoTo ExitImport
End If
ExitImport:
On Error Resume Next
ImportFileUsingSpecification = bReturn
Set oSpec = Nothing
Exit Function
End Function
Obviously you'll need to find the table name in the spec XML and use a placeholder on it as well. Let me know if you can't get it to work and i'll update for export.

Set cell value with VBA

I scan and save images with Wia using VBA in Microsoft Access.
The filepath to the saved image should be set as the value of the current cell.
I can't figure out how to do this but it seems like an easy task after learning how to use Wia.
Here is my current code that scans a document.
Function scanImage() As String
Dim imagePath As String
Dim folder As String
folder = "C:\Users\username\Pictures\scans\"
Dim tempName, obj
Set obj = CreateObject("Scripting.FileSystemObject")
tempName = obj.GetTempName
Dim filename
filename = Now
filename = Replace(filename, ".", "_")
filename = Replace(filename, " ", "_")
filename = Replace(filename, ":", "_")
imagePath = folder & filename & ".jpg"
Dim dev As Device
Dim wiaDialog As New WIA.CommonDialog
Dim wiaImage As WIA.ImageFile
Set dev = wiaDialog.ShowSelectDevice
Set wiaImage = wiaDialog.ShowAcquireImage
wiaImage.SaveFile (imagePath)
scanImage = imagePath
End Function
As comments have said - there's no cells in Access, and definitely no active cell.
You can add a record to a database using either of the methods below, but how do you plan on extracting that information again?
In Excel you just ask for the data in cell A1 for example, but in a database you generally ask for the data from a field or fields where another field on that same record is equal to some other values (either by supplying the 'other value' directly or by referencing other tables within the database).
So, for example, in your database you'd ask for the file paths of all files scanned on a certain date, or have some kind of description field to identify the file.
This would be written something like:
SELECT FilePath FROM Table2 WHERE DescriptionField = 'MyPhoto'
Anyway, the answer to get that single text string (imagepath) into a new record in a table is:
Sub InsertValueToTable()
Dim imagepath As String
imagepath = "<file path>"
'NB: The table name is 'Table2', the field (column) within the table is called 'FilePath'.
'One way to do it:
'DoCmd.RunSQL "INSERT INTO Table2(FilePath) VALUES ('" & imagepath & "')"
'Another way to do it:
Dim rst As dao.Recordset
Set rst = CurrentDb.OpenRecordset("Table2")
With rst
.AddNew
rst!FilePath = imagepath
.Update
.Close
End With
Set rst = Nothing
End Sub
Note - if you use a Text field in the database you'll be limited to 255 characters.

VBS Creating CSV file then adding extra rows to it

Below is my VBS code. I will admit, I am extremely new to this since I was give this as a job at work. I need to create a logon/logoff script that will capture certain information and store it in a csv file. I am able to get the information and store it in the csv file, but when I try to do it again, I want it to create another row and store the updated information there. I keep getting these asian characters. What seems to be the problem.
This is what I get on the second time I click my log off script:
਍潙牵琠硥⁴潧獥栠牥⹥਍
' ******************** Log Off Script **********************************
'Script to write Logoff Data Username, Computername to eventlog.
Dim objShell, WshNetwork, PCName, UserName, strMessage, strContents, logDate, logTime
Dim strQuery, objWMIService, colItems, strIP, rowCount
' Constants for type of event log entry
const EVENTLOG_AUDIT_SUCCESS = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("WScript.Shell")
Set WshNetwork = WScript.CreateObject("WScript.Network")
logDate = Date()
logTime = Time()
PCName = WshNetwork.ComputerName
UserName = WshNetwork.UserName
strMessage = "Logoff Event Data" & "PC Name: " & PCName & "Username: " & UserName & "Date: " & logDate & "Time: " & logTime
If (objFSO.FileExists("test.csv")) Then
WScript.Echo("File exists!")
dim filesys, filetxt
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set filesys = CreateObject("Scripting.FileSystemObject")
Set filetxt = filesys.OpenTextFile("test.csv", ForAppending, True)
filetxt.WriteLine(vbNewline & "Your text goes here.")
filetxt.Close
Else
rowCount = rowCount + 1
WScript.Echo("File does not exist! File Created!")
Set csvFile = objFSO.CreateTextFile("test.csv", _
ForWriting, True)
objShell.LogEvent EVENTLOG_AUDIT_SUCCESS, strMessage
csvFile.Write strMessage
csvFile.Writeline
End If
WScript.Quit
When in doubt, read the documentation. You're creating the file in Unicode format (3rd argument of CreateTextFile set to True):
Set csvFile = objFSO.CreateTextFile("test.csv", _
ForWriting, True)
but you open an existing (Unicode) file in ASCII format (4th argument of OpenTextFile not specified):
Set filetxt = filesys.OpenTextFile("test.csv", ForAppending, True)
Either open a file in Unicode format all of the time, or never.
Also, it's unnecessary to create more than one FileSystemObject instance. Just use the one you created at the beginning throughout the entire script. You can also use the same variable for the text stream object.
If you want to use Unicode format you need to change the above two lines into this:
Set csvFile = objFSO.CreateTextFile("test.csv", False, True)
...
Set csvFile = objFSO.OpenTextFile("test.csv", ForAppending, False, True)
otherwise into this:
Set csvFile = objFSO.CreateTextFile("test.csv")
...
Set csvFile = objFSO.OpenTextFile("test.csv", ForAppending)

Copy RTF text from Access to word table using VBA

Is there a way to copy a RTF text from a memo field in Access Database to Word document using VBA. I have this code at the moment but it produces html text (the text includes tags and not formatted).
' Query the database and get the sales for the specified customer
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Sales WHERE Sales.[ID] ='" & Forms![customers]![id] & "'")
'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst
Do Until rs.EOF = True
' Create file and add rtf text
Set ts = fso.CreateTextFile("c:\temp\temp.rtf", True)
ts.Write rs(3)
ts.Close
' Add a row
doc.Tables(1).Rows.Add
' Get the number of the added row to add data
i = doc.Tables(1).Rows.Last.Index
' Add sale to word table
doc.Tables(1).Cell(i, 2).Range.InsertFile "C:\temp\temp.rtf", , False
'Move to the next record. Don't ever forget to do this.
rs.MoveNext
Loop
Else
MsgBox "There are not records in the recordset."
End If
MsgBox "Finished." & i
rs.Close
Set rs = Nothing
Is there any other way to do this?
Note that the "Rich Text" option for Memo fields does not store the formatted text as RTF. The formatted text is stored as HTML, which is why you were seeing HTML tags in your text.
The following Access VBA code creates a Word document that contains formatted text and is saved as .rtf. If you're not committed to using RTF then the code could easily be modified to save the document as .doc or .docx.
Sub FormattedTextToWord()
Dim objWord As Object ' Word.Application
Dim fso As Object ' FileSystemObject
Dim f As Object ' TextStream
Dim myHtml As String, tempFileSpec As String
' grab some formatted text from a Memo field
myHtml = DLookup("Comments", "MyTable", "ID=101")
Set fso = CreateObject("Scripting.FileSystemObject") ' New FileSystemObject
tempFileSpec = fso.GetSpecialFolder(2) & "\" & fso.GetTempName & ".htm"
' write to temporary .htm file
Set f = fso.CreateTextFile(tempFileSpec, True)
f.Write "<html>" & myHtml & "</html>"
f.Close
Set f = Nothing
Set objWord = CreateObject("Word.Application") ' New Word.Application
objWord.Documents.Add
objWord.Selection.InsertFile tempFileSpec
fso.DeleteFile tempFileSpec
' the Word document now contains formatted text
objWord.ActiveDocument.SaveAs2 "C:\Users\Public\zzzTest.rtf", 6 ' 6 = wdFormatRTF
objWord.Quit
Set objWord = Nothing
Set fso = Nothing
End Sub