TransferText incorrectly imports strings like "FS###" as Currency - csv

I am using the VBA DoCmd.TransferText command to import data from a CSV text file into a new table in my Access database. I have run into an issue where the text data in the first three columns in some of the files is imported as currency. I cannot figure out what is happening.
Here is a test database along with one CSV that imports correctly (VollintineLines.csv) ...
PipeID,UpstreamMH,DownstreamMH,Diameter,GISLength,Status
WS010353S,WS010353,WS010163,36,227.1984614,Fully Surveyed as Phase Work
WS011155S,WS011155,WS011154,8,418.5435318,Not Surveyed
WS011154S,WS011154,WS011153,8,303.9618911,Fully Surveyed as Phase Work
... and one that doesn't (CourtLines.csv).
PipeID,UpstreamMH,DownstreamMH,Diameter,GISLength,Status
FS020628S,FS020628,FS020462,10,278.72,Not Surveyed
FS020463S-1,FS020463,FS020462,12,248.39,Not Surveyed
FS020216S,FS020216,FS020215,12,227.53,Fully Surveyed as Phase Work
(Please ignore the unnamed objects in the database, it was just to figure out what is going on here and I didn't bother naming things.)
Here is the import code, you have to enable the Microsoft Office 16.0 Object Library Reference.
Private Sub Command0_Click()
Dim Path As FileDialog
Dim FileName As Variant
DoCmd.SetWarnings False
DoCmd.Hourglass True
Set Path = Application.FileDialog(msoFileDialogFilePicker)
With Path
.AllowMultiSelect = False
.Title = "Select your File"
.Filters.Add "All Files", "*.*"
If .Show = -1 Then
For Each FileName In .SelectedItems
DoCmd.TransferText acImportDelim, , "TempPipeData", FileName, True
Next FileName
Else
MsgBox "No File Selected to Import."
End If
End With
DoCmd.SetWarnings True
DoCmd.Hourglass False
End Sub

You have apparently encountered a rather obscure bug affecting TransferText calls that do not use an Import Specification. (It is also discussed on another site here.)
Workarounds include:
Use an Import Specification as described in this answer.
Create the table first, specifying the desired column types (Text in this case), and then import from the CSV file into the existing (empty) table.
If neither of the above options is desirable, then you could use COM Automation to
launch an instance of Excel,
have Excel open the CSV file,
save it to XLS or XLSX,
use TransferSpreadsheet in Access VBA to import the Excel data, then
delete the temporary XLS[X] file.

Related

DoCmd.TransferText in MS Access not working ("engine could not find the object")

I have a table called "Tk20F7_agg" that I am trying to export as a .txt file with custom specifications. The code is below but when I run it, I get this error:
"The Microsoft Access database engine could not find the object 'Tk2020181903#txt.'"
TempName01 = "Tk20" & Format(Date, "yyyyddmm")
ExportPath = DLookup("Export_Path", "OmniDB_system01")
Application.FileDialog(msoFileDialogSaveAs).Title = "Export Tk20 File7 (Testing)"
Application.FileDialog(msoFileDialogSaveAs).InitialFileName = TempName01 & ".txt"
intChoice = Application.FileDialog(msoFileDialogSaveAs).Show
If intChoice <> 0 Then
strPath = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
End If
DoCmd.TransferText acExportDelim, "Tk20_File7_spec", "Tk20F7_Agg", TempName01 & ".txt", True
Any help on fixing this would be greatly appreciated!
In my experience, I've found that this particular (and rather misleading) error message can be produced when the structure of a query or table is modified and the associated Export Specification is not updated to reflect the changes.
To resolve the error, I would suggest exporting the target object 'manually' using the Export Text File wizard, and re-save the Export Specification.
I will also add for other readers - the key here is "with custom specifications".
Without those - - one can reconfigure a table/query and a saved export will work because it is just called by the object name.

Invalid Argument on import code that works elsewhere

At a loss, I have an import module used to help my less technically proficient coworkers to import data to an access database for processing. I use the following code for 8 difference text imports, they all work except for one. I can manually import using the import specification so that is not the issue, I have triple checked the table and import spec name, also not the issue, can anyone tell me why access is throwing the error?
Function import_Headcount()
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Set db = CurrentDb
Dim path As Variant
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE * FROM [tbl_Headcount]"
With fd
.AllowMultiSelect = False
If .Show = -1 Then
For Each path In .SelectedItems
DoCmd.TransferText acImportDelim, "National Headcount", "tbl_Headcount", path, False
Next path
Else
MsgBox ("Import for Headcount cancelled")
Exit Function
End If
End With
Set fd = Nothing
db.Execute "qry_Update_Headcount_Fields"
DoCmd.SetWarnings True
MsgBox ("Import of Headcount complete")
End Function
It is throwing a "3001" error on the DoCmd.TransferText line, as I have said I have copy and pasted this small function 8 times with different tables and import specs and cannot see why this one is not working. Thanks for the help!
Have you tried to use square brackets in specification name?
DoCmd.TransferText acImportDelim, "[National Headcount]", "tbl_Headcount", path, False
Sounds like you are on the right track on the troubleshooting side... Keep ruling out the variables until you can pinpoint the issue.
I would suggest installing V-Tools, a freeware Access add-in. This has a utility for managing/editing import specs. This would be the first tool I would reach for in debugging the import issue. It includes a number of other helpful tools, but for the project at hand, I think you will find the Import/Export Specifications form very helpful.
Here is a screen shot of an import spec we use on a daily basis:
As you can see, this utility exposes far more options than the built-in wizards when it comes to importing and exporting data.
Hope that helps!

How do I appropriately use my customized query export VBA with the FileDialog option?

This is directly related to the following two posts:
How do I export 2 queries to a single worksheet in excel from access
Saving a custom export from an Access 2007 script
I am using Access 2010, and I have created a command button on a form with the following VBA in its Click event. The VBA allows me to export multiple queries, into different worksheets, within the same Excel file:
VBA #1: This exports multiple queries into one Excel file
Private Sub CommandBtn_Click()
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "Query1", "test1.xlsx", True, "NameofWorksheet"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "Query2", "test1.xlsx", True, "NameofSecondWorksheet"
End Sub
Edit(4/7/2014: 11:26 AM): Clarified what I want below.
Desire
I want to add the following feature to my command button's Click event: A "Save As" dialog window that prompts the user to choose where to save the newly created Excel file (test1.xlsx).
Challenges:
I do not know what VBA code would be appropriate to use for doing so. I ran into the FileDialog(msoFileDialogSaveAs) option when doing my research on this. However, I have not been able to successfully use it to produce what I want.
I think you want to get the file selection before DoCmd.TransferSpreadsheet, because the file selection is the transfer target.
I'm not sure exactly what you want, but I think this should be a step closer ...
Private Sub CommandBtn_Click()
Dim fileSelection As Object
Dim strPath As String
Set fileSelection = Application.FileDialog(2)
With fileSelection
.AllowMultiSelect = False
If .Show = True Then
strPath = .SelectedItems(1)
' use strPath with TransferSpreadsheet ...
'DoCmd.TransferSpreadsheet
Else
MsgBox "no file selected"
End If
End With
End Sub

VBA Access import Field doesn't exist in destination - Fieldname is garbled

I'm importing a *.csv file into an Access table with the following code:
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
If .Show = -1 Then
DoCmd.TransferText TransferType:=acImportDelim, _
TableName:="New References", _
FileName:=.SelectedItems.Item(1), _
HasFieldNames:=True
TextReferenceImport = .SelectedItems.Item(1)
Else
TextReferenceImport = ""
End If
End With
Set fd = Nothing
However, I get the following error:
Microsoft Visual Basic
Field 'Name' doesn't exist in destination table 'New references.'
Obviously, the field name in both Access and the *.csv file is "Name". This is also the first column of the *.csv file. I have also set HasFieldNames to False, and changed the first columns name to F1 in access, and that seemed to work so I don't think there is anything wrong with the import.
Why does access read these strange characters that are not present in the *.csv or table, that then disrupt the import?
Those  characters are the UTF-8 BOM (byte order mark).
Unless it's practical to strip them out of your CSV before doing the import, I think you will need to create an Import Specification.
Begin an import manually from the Access user interface. After selecting your CSV file, select "First Row Contains Field Names" from the second page of the "Import Text Wizard". Then click the "Advanced" button and select "Unicode (UTF-8)" for the "Code Page" property on the import specification dialog. And then click "Save As" to give your import specification a name.
Then you can use that saved import specification when you call DoCmd.TransferText from VBA. Here is an example I tested in Access 2007 ...
DoCmd.TransferText TransferType:=acImportDelim, _
SpecificationName:="YourTable Import Specification", _
TableName:="YourTable", _
FileName:="C:\Users\hans\Documents\YourTable.csv", _
HasFieldNames:=True

simple import form in Access

how to create an access form which has import excel file button. and after selecting excel file it automatically creates a table in the database with collumn headers as excel first row and data as excel other rows. if you think i am not putting any effort please give me suggestion or reference and ill do it on my own.
For versions of Access since 2003, you can use the File Dialog to allow the user to browse for the file they want, prior to that, you can use API calls. If this is overkill for you, you can have the user type in the file name and path, but you will have to check that it exists using code (Dir may suit).
It would be best to use TransferSpreadsheet method of the DoCmd object (available in any version of Access from, AFAIK, 1997 onward) to import the spreadsheet. This can be run as VBA (code) or a macro.
If we assume that you are able to create a form and wire up a button you have two issues:
The file open dialog.
Triggering the import.
For 1 you should be able to use the standard Microsoft file dialogs - my VB.OLD and Access are spectacularly rusty (no access 2007) but you can reference the appropriate COM assemblies from Access after which it becomes fairly easy.
2 is a bit more interesting - I beleive you can pretty much do this by menu selection from within access in which case, at least as a first step, you should be able to automate the same steps - pretty much anything you can do from a menu you can also do by calling the relevant command from VBA. The more complex solution would be to create VBA logic to create a linked table that links to the Excel file and then do a create table query and then drop the link.
In terms of effort, the form is something one would expect you to be able to do without much help - however automating something like an import from excel is not necessarily obvious.
An example using Access 2003 would be as follows for selecting a file:
Dim fDialog As Office.FileDialog
Dim strFile As String
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.InitialFileName = "C:\temp\*.xls"
.Filters.Clear
.Filters.Add "Excel file", "*.xls"
.Filters.Add "All Files", "*.*"
If .Show = True Then
strFile = .SelectedItems(1)
End If
End With
Debug.Print strFile
Note you would need to add a Reference to the Office 12 Object Library
To Import the file you can use the TransferSpreadsheet Function of the DoCmd Object. For E.g.
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "ExcelImport", strFile, True
The Access table called ExcelImport would have to already exist in the database.