473,326 Members | 2,099 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

TransferText

Bonjour,

La première colonne de mon fichier texte (séparateur points-virgules)
contient des valeurs alphanumériques (1,2a,3u etc). Je constate que
seules les valeurs numériques sont importées dans la première
colonne de ma table "MaTable".

Expression vba utilisée : DoCmd.TransferText acImportDelim, ,
"MaTable", "C:\fichier.txt", True

NE ME PARLER PAS DE FORMAT D'IMPORTATION car j'ai 125 fichiers à plat
et tous différents ; je ne peux donc me permettre de créer (via
l'assistant d'importation) 125 formats d'importation !

Est-ce à dire qu'Access suppose par défaut que la première colonne
d'une fichier texte est numérique sans spécification de format
d'importation ?

J'ai lu des messages à ce propos mais aucun n'a répondu clairement.
Merci pour votre aide.

Nov 13 '05 #1
4 7991
axelleforever wrote:
Bonjour,

La première colonne de mon fichier texte (séparateur points-virgules)
contient des valeurs alphanumériques (1,2a,3u etc). Je constate que
seules les valeurs numériques sont importées dans la première
colonne de ma table "MaTable".

Expression vba utilisée : DoCmd.TransferText acImportDelim, ,
"MaTable", "C:\fichier.txt", True

NE ME PARLER PAS DE FORMAT D'IMPORTATION car j'ai 125 fichiers à plat
et tous différents ; je ne peux donc me permettre de créer (via
l'assistant d'importation) 125 formats d'importation !

Est-ce à dire qu'Access suppose par défaut que la première colonne
d'une fichier texte est numérique sans spécification de format
d'importation ?

J'ai lu des messages à ce propos mais aucun n'a répondu clairement.
Merci pour votre aide.


The code below my sig may help. It converts any variable length ASCII
file to a CSV file with quotes (") around all fields to make Access
think everything is text. Watch out for wrapping, people don't like
attachments in this group, even text ones. And don't copy the BMW grill,
it won't compile :-)

Translation by Lycos / Traduction par Lycos

Le code au-dessous de mes sig peut aider. Il convertit n'importe quel
fichier ASCII de longueur variable en dossier de CSV avec des citations
(") autour de tous les champs pour faire l'Access penser tout est texte.
Observez dehors pour s'envelopper, les gens n'aiment pas des
attachements dans ce groupe, même texte ceux. Et ne copiez pas le gril
de BMW, il ne compilera pas :-)

--
[OO=00=OO]

Option Compare Database
Option Explicit

Public Function ParseFileToTemp(pstrFile As String, pstrDelim As String,
pstrQuote As String, pfHasFieldNames As Boolean, Optional plngRows As
Long = 0, Optional pstrCommentchar As String = "")
' Error Trapped: 06/10/2004 16:41:21 sa

On Error GoTo ParseFileToTemp_Err

' TB: Takes a variable length delimited file and creates a CSV file
with it then
' links it as a table, even CSV files are put through this as we
basically make
' every column into text in the resultant CSV file there can be no
mistake in
' the way Access interprets the data, e.g. it can make assumptions
that a field
' is numeric then barf when it encounters text in it. Also foreign
formatted dates
' will come through as text and be handled by another procedure.

Dim hFileIn As Integer
Dim hFileOut As Integer
Dim strTempFile As String
Dim strText As String
Dim strColumn() As String
Dim i As Integer
Dim lngRow As Long
Dim varStart As Variant

Const cstrTempTable As String = "tblImportWizTemp"
Const cstrQuote As String = """"

varStart = Now()
' drop the linked CSV file table
DropImportTable cstrTempTable

' open our input and output files
hFileIn = FreeFile
Open pstrFile For Input As #hFileIn
hFileOut = FreeFile
strTempFile = Environ("TEMP") & "\MA_Import.CSV"
Open strTempFile For Output As #hFileOut
SysCmd acSysCmdInitMeter, "Parsing file", LOF(hFileIn)
' loop and get all the fields into text
Do Until EOF(hFileIn)
Line Input #hFileIn, strText
SysCmd acSysCmdUpdateMeter, Loc(hFileIn) * 128
Select Case True
Case Len(Trim(strText)) = 0
' ignore line
Case Left(strText, Len(pstrCommentchar)) = pstrCommentchar
And Len(pstrCommentchar) > 0
' ignore line
Case Else
' split the fields into an array
strColumn = SplitFields(strText, pstrDelim, pstrQuote)
' now re-create the CSV line making it all text fields
strText = cstrQuote & strColumn(0) & cstrQuote
For i = 1 To UBound(strColumn)
strText = strText & "," & cstrQuote & strColumn(i)
& cstrQuote
Next
Print #hFileOut, strText
' check if sample data wanted
lngRow = lngRow + 1
If lngRow >= plngRows And plngRows > 0 Then
Exit Do
End If
End Select
Loop
' close files
Close #hFileIn
Close #hFileOut
SysCmd acSysCmdRemoveMeter

'Debug.Print "Parsing text file: "; lngRow & " row(s): " &
DateDiff("s", varStart, Now()) & " seconds"

' re-link the table.
DoCmd.TransferText acLinkDelim, , cstrTempTable, strTempFile,
pfHasFieldNames

ParseFileToTemp_Exit:
On Error Resume Next
SysCmd acSysCmdRemoveMeter
DoCmd.Hourglass False
Exit Function
ParseFileToTemp_Err:
Select Case Err
Case Else
'LogMsgBox Err, Err.Description, 16, "Error #" & Err & " In
ParseFileToTemp()"
' bubble up, we want the calling procedure to handle the error
Err.Raise Err.number, "ParseFileToTemp", Err.Description
End Select
Resume ParseFileToTemp_Exit

End Function

Function DropImportTable(pstrTable As String)
' TB: Bet you cannie work out what this does :-)
' actually uses DAO rather than SQL Drop as at time of writing SQL
Drop didn't work, table still there :-(
On Error Resume Next
CurrentDb.TableDefs.Delete pstrTable
End Function

Private Function SplitFields(pstrtext As String, pstrDelim As String,
pstrQuote As String) As String()
' TB
' Usual Split() function won't work for our strings as the
delimiter may be
' just a comma or may be a comma with quotes or combination
' e.g.
' 37740,"DRG-003-C",1,"0","a description, with a comma in
it",2/12/2003 00:00:00,16,1076,,,725,,5,15180,,,,,,0

Dim strReturnArray() As String
Dim strTemp As String
Dim strElement As String
Dim lngElements As Long
Dim strDelim As String

strTemp = pstrtext
Do While Len(strTemp)
If Len(pstrQuote) Then
strDelim = String(Abs(Left(strTemp, 1) = pstrQuote),
pstrQuote) & pstrDelim
Else
strDelim = pstrDelim
End If
strElement = GetFirstElement(strTemp, strDelim)
If Len(strTemp) Then
strTemp = Mid(strTemp, Len(strElement) + Len(strDelim) + 1)
'Debug.Print strTemp
lngElements = lngElements + 1
ReDim Preserve strReturnArray(1 To lngElements)
' Strip off first " if existing
strElement = Mid(strElement, 1 + Abs(Left(strElement, 1) =
""""))
Do While Right(strElement, 1) = """"
strElement = Left(strElement, Len(strElement) - 1)
Loop
strReturnArray(lngElements) = strElement
End If
Loop

SplitFields = Split(Join(strReturnArray(), "~~~moo!~~~"), "~~~moo!~~~")

End Function
Private Function GetFirstElement(sStr As String, strDelimiter As String)
As String
On Error GoTo Err_GetElement
' TB: Nicked from Jezzer's GetElement :-)
Dim nX As Integer
Dim nY As Integer
Dim nC As Integer

' Want first element which is a special case.
nX = InStr(1, sStr, strDelimiter, vbTextCompare)
If nX = 0 Then
' There is no 'strDelimiter' in the string, therefore return
the whole string.
GetFirstElement = sStr
Else
GetFirstElement = Mid(sStr, 1, nX - 1)
End If

Exit_GetElement:
Exit Function

Err_GetElement:
Select Case Err.number
Case 5 ' Invalid procedure call.
' Caused by a series of empty keys passed and a call to
'mid' can not be carried out as a position is negative.
' Return the empty string
GetFirstElement = ""
Resume Exit_GetElement
Case Else
' Unexpected error - return empty string.
GetFirstElement = ""
Resume Exit_GetElement
End Select
End Function
Nov 13 '05 #2
Je ne suis pas très partisans du code à outrance. Qu'est-ce que ce
fichier schema.ini ? J'ai 125 fichiers textes à importer dans 125
tables. Je peux à la rigueur créer un fichier schema.ini mais quel
est son format ? Mon poste de travail ne recense aucun schema.ini
malgré plusieurs sauvegardes de format d'importation !

Nov 13 '05 #3
axelleforever wrote:
Je ne suis pas très partisans du code à outrance. Qu'est-ce que ce
fichier schema.ini ? J'ai 125 fichiers textes à importer dans 125
tables. Je peux à la rigueur créer un fichier schema.ini mais quel
est son format ? Mon poste de travail ne recense aucun schema.ini
malgré plusieurs sauvegardes de format d'importation !


Je ne sais d'aucun fichier de schema.ini.

De ma position je vois 2 choix :

1. Employez le code pour convertir le dossier en format que l'Access
importera facilement ou...

2. Créez 125 caractéristiques d'importation.

--
[OO=00=OO]
Nov 13 '05 #4
Trevor Best wrote:
1. Employez le code pour convertir le dossier en format que l'Access
importera facilement ou...


apologies, dossier = fichier (stupid Lycos :-)

--
[OO=00=OO]
Nov 13 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Sue | last post by:
Using WindowsXP and AccessXP in 2000 Mode When I run the following code, I get error 3027 "Cannot Update. Database or object is read only." StrFolder = "C:\Comic Box\WebStore Interface...
2
by: BigData | last post by:
I am attempting to create a delimited text file by using DoCmd.Transfertext as shown here. DoCmd.TransferText acExportDelim, "ExportSpec", "QryFinalExport", "Fileout.txt" This works fine as...
6
by: Vladislav Moltchanov | last post by:
I have discovered a couple of years ago, that import with DoCMD.TransferText for CSV text file doesn’t work in Acc2000, while it works perfectly in ACC97. which has been discussed on this...
11
by: Shyguy | last post by:
I need to import a text file pretty much daily. I download the file and change the name to a standard name and then run the code to import the file into a table in my database. The problem is...
3
by: Typehigh | last post by:
I am a pretty saavy user, but I am having a real problem with the DoCmd.TransferText operation. I manually used the File>Get External Data> Import routine to set up an import specification. It...
3
by: holdemfoldem | last post by:
Hi. I'm new to this board and have a few questions about using the method referred to in the topic of this message. I have manually transferred over 1/2 million records from a text file into my...
3
by: Oliver Gabriel | last post by:
Hi, i want to export a table for later import, using vba. That´s my code: export: filename = "C:\HVOtabelle.txt"
3
by: Jim M | last post by:
I am trying to 'grab' a backend data path and filename from a text file (to be used when updated front ends are installed by users). I store this information by running: DoCmd.TransferText...
0
by: Sean Howard | last post by:
I have a strange problem linking tab delimited text files in Access 2000 (I am running Windows XP), please try this and let me know if I am going mad. Step 1. Create the tab-delimited text...
0
by: stuart | last post by:
I seem to have a problem with the use of the TransferText function. In 2 applications that I have, every few months, it seems to not export a few records from a table. In another application,...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.