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
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.
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.
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
I've read through a couple similar posts, but not found a solution for this issue:
I have a form with an unbound rich text, multiline textbox named tbxNote. When the textbox is exited, I use VBA code to create an SQL string which I subsequently execute to UPDATE a table field [Note] with the value in the unbound textbox. [Note] is a "Long Text" field (from my understanding, "Long Text" is equivalent to what used to be called a "Memo" field). The backend is an Access database.
Problem is: Only the first 250 characters of what is in tbxNote get stored in the target table field [Note] even though other "Long Text" fields in other tables are accepting values much longer than 250 characters. So, it does not seem to be an issue with the field type or characteristics in the backend table.
Furthermore, if I manually open the target table and paste 350 characters into the same [Note] field in the target table, all 350 characters get stored. But, if I load up that record into the form or put the same 350 characters into the form's tbxNote textbox, only 250 characters are pulled into tbxNote or saved out to [Note].
Is there a way to store more than 250 characters in an unbound textbox using an UPDATE SQL in code?
In case it matters, here's the SQL code that I used to prove only 250 of 350 characters gets saved to the table field [Note]:
dbs.Execute "UPDATE tblSupeGenNotes " & _
"SET [NoteDate] = #" & Me.tbxNoteDate & "#, " & _
"[SupeType] = " & Chr(34) & Me.cbxSupeType & Chr(34) & ", " & _
"[SupeAlerts] = " & alrt & ", " & _
"[Note] = " & Chr(34) & String(350, "a") & Chr(34) & " " & _
"WHERE [SupeGenNoteID] = " & Me.tbxSupeGenNoteID & ";"
Of course, normally I'd have Me.tbxNote instead of String(350, "a") but the String proves that only 250 of the 350 characters get stored in the [Note] field.
I must be missing something simple, but I cannot figure it out.
Unfortunately, you posted test code works, but you FAILED to post your actual update string that fails. A common (and known) problem is if you include a function (especially aggregates) in your SQL, then you are limited to 255 characters.
In fact this can apply if you have function(s) that surrounds the unbound text box and is used in the query.
So such an update should and can work, but introduction functions into this mix can cause problems with the query processor.
If you included the actual update, then the above issue(s) likely could have been determined.
So the workarounds are:
Don’t use any “functions” directly in the SQL update string, but build up the string.
So in place of say:
Dbs.Execute "update tblTest set Notes = string(350,’a’)"
Note how above the string function is INSIDE the sql.
You can thus place the function(s) OUTSIDE of the query and thus pre-build the string - the query processor is NOT executing nor will it even see such functions.
So we can change above to as PER YOUR EXAMPLE:
Eg:
Dbs.Execute "update tblTest set Notes = ‘" & string(350,’a’) & "’"
(this is how/why your posted example works, but likely why your actual code fails). So functions can (and should) be moved out of the actual query string.
Also make sure there is NO FORMAT in the formatting for the text box, as once again this will truncate the text box to 255.
And as noted here the other suggestion is to consider using a recordset update in place of the SQL update.
Using a recordset can often remove issues of delimiters and functions then become a non issue.
So such SQL updates can work beyond 255 characters, but functions need to be evaluated in your VBA code before the query processor gets its hands on the data as per above examples.
And as noted remove any “format” you have for the text box (property sheet, format tab).
#HansUp's suggested trying a DAO recordset to update the table. That did the trick! Thank you, HansUp. HansUp requested that I post the answer, so, here is the code that worked for anyone else who comes across this thread:
Dim dbs As DAO.Database
Dim rsTable As DAO.Recordset
Dim rsQuery As DAO.Recordset
Set dbs = CurrentDb
'Open a table-type Recordset
Set rsTable = dbs.OpenRecordset("tblSupeGenNotes", dbOpenDynaset)
'Open a dynaset-type Recordset using a saved query
Set rsQuery = dbs.OpenRecordset("qrySupeGenNotes", dbOpenDynaset)
'update the values vased on the contents of the form controls
rsQuery.Edit
rsQuery![NoteDate] = Me.tbxNoteDate
rsQuery![SupeType] = Me.cbxSupeType
rsQuery![SupeAlerts] = alrt
rsQuery![Note] = Me.tbxNote
rsQuery.Update
'clean up
rsQuery.Close
rsTable.Close
Set rsQuery = Nothing
Set rsTable = Nothing
AH! Another bit to the solution is that prior to using the DAO recordset, I was pulling values from the table into a listbox and from the listbox into the form controls (instead of directly into the form controls from the table). Part of the problem (I believe) was that I was then populating the form controls from the selected item in the listbox instead of directly from the table. I believe listboxes will only allow 255 characters (250 characters?) in any single column, so, everytime I pulled the value into the textbox from the listbox, the code was pulling only the first 255 characters into the textbox. Then, when the textbox was exited, the code was updating the table with the full textbox text, but when it was pulled back into the form through the listbox, we'd be back down to 255 characters. Of course, when I switched to the DAO approach, I also switched to reading the textbox value directly from the table instead of pulling it from the listbox.
Moral: Beware of pulling Long Text values through a listbox!
Thanks to everyone who helped me solve this. Sorry for such a newbie error seeming more complicated than it was.
I assume you are using the SqlClient library. In which case, I recommend trying SqlParameters rather than creating a SQL string the way you are. With the SqlParameter you can specify the size of each parameter. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2 . I am a C# dev so my apologies about doing the example code below in C#:
string param = "Hello World";
byte [] encodedStr = Encoding.UTF8.GetBytes(param);
SqlParameter sqlParam = new SqlParameter();
sqlParam.Size = encodedStr.Count; // uses byte count
you could condense it by calling Encoding.UTF8.GetBytes(param).Count. Anyways, this might fix your issue
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