How to import text file into existing Access table using Visual Basic(button click) (Visual Basic 2015)) [duplicate] - vb.net

I am trying to automate the adding of new text files, which all have the same (known) layout.
The columns are separated using tabs (the TAB button). My question is, is it possible to do this in VBA? Like, in the access wizard for importing text files?
I am using the DoCmd.TransferText method in VBA

You'll need to go through the wizard once to make your specification file. TO do this import your text file like normal but before you get too deep into the wizard click on the bottom left, the "Advanced..." button. This is where you make your spec file.
Make ll these columns match your input file, data types and all. Be sure to select the {tab} field delimiter and the appropriate text qualifier if you are using one.
Save your spec (which can later be edited by coming back to this same screen and clicking Specs... then saving over your old one)
Now you can use in VBA like this
DoCmd.TransferText acImportDelim, "your spec name", "destination table name", sourceFilePath
There is a parameter HasFieldNames that you'll have to decide if it is true or false based on your file.

With the import wizard the downside is that for even the slightest change in file format, you'll have to click through all those steps yet again to get the import working.
Check out #Remou's answer in ms Access import table from file in a query for a way to do it in straight SQL. I am actually using the same method in a project of mine. I use something like this (see my link for the details):
insert into MyTable (column-list...)
select (column-list...)
from [data-source-specifications].[file-name]
any-other-clauses...;
Just one caveat. If you put this SQL syntax into a normal Access query object, there's a good chance that Access will mangle it to the point where it won't even be able to open the query object. So compose and save the query in a text file while you try it out in Access. Once the query is tested and working, save it in a VBA subroutine so that Access will run it exactly as is, like so:
sub MyTableImport()
sqlStr = " insert into MyTable (column-list) " ' leave a space at the
sqlStr = sqlStr & "select (column-list...) " ' end of each line of the string
sqlStr = sqlStr & "from [data-source-specifications].[file-name] "
sqlStr = sqlStr & "any-other-clauses... ;"
DoCmd.RunSQL sqlStr
end sub

Related

MS Access Issue

Hello Stackoverflow community!
I have run into an issue and I'd love some advice.
I'm working with MS Access and I am trying to append two particular fields from one table to another; however this implementation is in a form and it gets a little complicated... So, I'll explain everything the best that I can
BACKGROUND INFORMATION:
First and fore most, I have two tables; one of which is a linked excel spread sheet from another directory (who is not willing to change any formatting what so ever, so I CANNOT make ANY changes to this file and it is being updated on a daily basis). This excel spreadsheet is very large and contains somewhere around 50 columns
The other table is not anywhere near as large but has around 20 columns and is meant to extract two columns from the excel spreadsheet (the first column and the third column). I'm trying to make a form for this database to be as user-friendly as possible and not many people in my office are familiar with the technicalities of Access queries and programming in VBA.
THE SITUATION:
On my form, the user will enter data into TextBoxA, from there they will click a button; this button will trigger a search through the linked excel spreadsheet for the data that was typed into TextBoxA. It will then copy the data from Field1 (which was the typed data) and Field3 and append these selected fields into the first two fields of the table in my Access Database. All of this is being done through a segment of VBA code
Private Sub CmdCloseForm_Click()
If IsNull(Me.TextBoxA) Or Me.TextBoxA = "" Then
MsgBox ("Field is empty, please try again!")
Else
Dim VendorNum As String
SearchingValue = Me.TextBoxA
Dim SQL As String
SQL = "INSERT INTO tbleRecord (Field1,Field2)" & _
"SELECT * " & _
"FROM tbleLinkedExcel " & _
"WHERE Field1 = '" & SearchingValue & "';"
DoCmd.RunSQL SQL
End If
End Sub
So the biggest issue here is that in Field1, and every time I try to run the code,
I receive an error; which I am assuming it is because of the space (unfortunately I cannot give the ACTUAL variable names out as it is confidential)
ERROR MESSAGE
The INSERT INTO statement contains the following unknown field name: 'FIELD 1'. Make sure you have typed the name correctly, and try the operation again.
The thing is, is that this 'FIELD 1' variable/name is not in my code, but in the linked excel spreadsheet (again, I am not able to change ANYTHING on this spreadsheet).
Thanks guys!

Insert value from one table to another by pressing a button

I have a select query called "tbl_Update" and a table called "tbl_A" in Access DB. I would like to press on on a button, which makes the following:
looks in fields "KW" and when they match (in this example below, the value "2016.45" are matching), then insert the value of "tbl_update.CA041073p" into "tbl_A.CA041073p". Seems to be very easy, but getting always Errors to do it. Any simple solutions how to do it? Thanks!
My code is the following and it is giving me the Error 3037:
Public Function Update()
DoCmd.RunSQL "Update tbl_A INNER JOIN tbl_Update " & _
"ON tbl_A.KW = tbl_Update.KW " & _
"SET tbl_A.CA041073p = [tbl_Update].[CA041073p] "
End Function
One quite likely reason is that the user running the program doesn't have read-write access to the database file, especially if it is located in program files folder.
So check the directory and file permissions and modify them if needed. You can also consider changing the location of the database file to another, more easily accessible folder.

Export Access Query WITHOUT Formatting

Relatively simple, but I can't seem to work it out. I want to export a query from access into a .csv (tab or comma delimited). When I do it manually through the wizard it works fine. But when I do it via vba, it comes complete with dash formatting that looks like the borders in the table!
I tried two methods and got the same results
DoCmd.OutputTo acOutputQuery, "Qry_GRADE", "MS-DOSText(*.txt)",_
"grade.csv", True, *ExportSpec*, , acExportQualityScreen
I used it with or without "ExportSpec", which is a specification I created when exporting manually.
This is the second method:
Dim testSQL As String
Dim qd As DAO.QueryDef
testSQL = "SELECT * FROM Qry_Grade"
Set qd = db.CreateQueryDef("tmpExport", testSQL)
DoCmd.TransferText acExportDelim, , "tmpExport",_
"C:\Users\Databoe\Documents\KidsTV\grade.csv"
db.QueryDefs.Delete "tmpExport"
This is a solution I've found which seems like overkill
And this is what the output looks like:
You can see it's not actually split any of the columns when opening the file in excel and that every second line is just a string of "-"'s
What about DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, myQueryName, myExportFileName, True for direct excel file export.
I tried your approaches, but I only get formated text with your first try DoCmd.OutputTo acOutputQuery, "Qry_GRADE", "MS-DOSText(*.txt)",_
"grade.csv", True, *ExportSpec*, , acExportQualityScreen which is as expected because it's a text export not csv.
With your second method I always get an excel compatible result. Maybe you have an error trap that hides an error and the first grade.csv is not overwritten. Use a different filename for the second method to prevent that.
Found a second trap. You don't specify full file path in first method, but in second. If C:\Users\Databoe\Documents\KidsTV is not your default document path, you have 2 grade.csv in different folders, but you maybe think that you only have one that gets overwritten.
I just ran into this problem myself, and found a great work around. It doesn't save as a .csv, but you can save as a comma delimited .txt file.
Use the export wizard on the External Data tab to export your query as a .txt file without formatting.
Once the file is exported you get a dialogue box asking if you want to save export steps. Click the box and save the export.
There is an action available in the Macro wizard called "Run Saved Import/Export." Select this action and choose your saved export from the dropdown menu.
Very frustrating that even now I cant seem to make Access export a simple csv file. I do not know why they think I need pretty formatting. Try this: open Excel, Click Get Data, From Database, From MicroSoft Access Database. Select the Access Database you wish to export from. Select the table/query we want saved as an csv. This will set up a link to this table. Once imported, save the Excel file to an csv file.

How to do a MS Access Update query for a table in external database

Im trying to perform an update query on a table that its on a separate database, so far i have this SQL:
UPDATE [;database=C:\QA_Daily_YTD_Report_Export.accdb].[YTD-Daily_Report] AS EXT_DB
SET EXT_DB.Category1 = "1"
WHERE (EXT_DB.Category1 = "status1");
When i run this it returns an "invalid operation" error. Any idea what im doing wrong?
I would recommend linking the table [YTD-Daily_Report] into your database because you can easily put the update query into your code without having your code execute the connection to the other database.
You can link a table in Access by clicking on the External Data. Then click on the Access symbol.
You should then get a dialog box like this:
Be sure you choose the second radio button because you don't want to import the data from the database, just link it.
Navigate to the location of the Database and click on it. Then make sure your database is shown in the dialog box above and click okay.
You should then get a dialog box like this one that will show the table you won't. Highlight it and click okay. Now you can rename the linked table with any name you want and this will be a much less of a stumbling block for your work.
Try to omit ;database=
UPDATE [C:\QA_Daily_YTD_Report_Export.accdb].[YTD-Daily_Report] AS EXT_DB SET EXT_DB.Category1 = "1" WHERE (EXT_DB.Category1 = "status1");
I ended up using VBA in a form, just in case someone is wondering how here it is:
Dim SQL As String
Dim db_external As Database
Set db_external = OpenDatabase(CurrentProject.Path & "\QA_Daily_YTD_Report_Export.accdb")
SQL = "UPDATE [YTD-Daily_Report]" & Chr(13) & _
"SET [YTD-Daily_Report].Category1 = '" & New_value & "'" & Chr(13) & _
"WHERE ([YTD-Daily_Report].Category1= '" & Look_up_value & "');"
db_external.Execute SQL

Importing a text with separators

I am trying to automate the adding of new text files, which all have the same (known) layout.
The columns are separated using tabs (the TAB button). My question is, is it possible to do this in VBA? Like, in the access wizard for importing text files?
I am using the DoCmd.TransferText method in VBA
You'll need to go through the wizard once to make your specification file. TO do this import your text file like normal but before you get too deep into the wizard click on the bottom left, the "Advanced..." button. This is where you make your spec file.
Make ll these columns match your input file, data types and all. Be sure to select the {tab} field delimiter and the appropriate text qualifier if you are using one.
Save your spec (which can later be edited by coming back to this same screen and clicking Specs... then saving over your old one)
Now you can use in VBA like this
DoCmd.TransferText acImportDelim, "your spec name", "destination table name", sourceFilePath
There is a parameter HasFieldNames that you'll have to decide if it is true or false based on your file.
With the import wizard the downside is that for even the slightest change in file format, you'll have to click through all those steps yet again to get the import working.
Check out #Remou's answer in ms Access import table from file in a query for a way to do it in straight SQL. I am actually using the same method in a project of mine. I use something like this (see my link for the details):
insert into MyTable (column-list...)
select (column-list...)
from [data-source-specifications].[file-name]
any-other-clauses...;
Just one caveat. If you put this SQL syntax into a normal Access query object, there's a good chance that Access will mangle it to the point where it won't even be able to open the query object. So compose and save the query in a text file while you try it out in Access. Once the query is tested and working, save it in a VBA subroutine so that Access will run it exactly as is, like so:
sub MyTableImport()
sqlStr = " insert into MyTable (column-list) " ' leave a space at the
sqlStr = sqlStr & "select (column-list...) " ' end of each line of the string
sqlStr = sqlStr & "from [data-source-specifications].[file-name] "
sqlStr = sqlStr & "any-other-clauses... ;"
DoCmd.RunSQL sqlStr
end sub