How to use concatRelated in MS Access 2007 - ms-access-2007

Want to list department name then all employees working under it. need to generate report using it.
i tried using sub queries, group by, DISTINCT
Department
First Name Last Name Salary

First you sholud add New Module in ms access
In Access, open the code window (e.g. press Ctrl+G.)
On the Insert menu, click Module. Access opens a new module window.
Paste in the function below.
On the Debug menu, click Compile, to ensure Access understands it.
SELECT Distinct
tbl1.field,
ConcatRelated("tbl2.fileld","tbl2","id=""" & [Id] & """ and name=""" & [name] & """") AS Employee
FROM tbl1;

Related

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.

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

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

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

MS Access SQL to copy part of a record displayed on a form, insert into same table as new record, and display the new record on a form

I have inherited a Microsoft Access 2010 database that is used to keep position/employee information in a single table. The table has an auto-number field for each record. The database has a form – ScreenB – that uses a query to pull and display in ScreenB a single record based on search criteria (Personnel Number, Last Name, Social Security Number, etc.) entered by the user. The record contains approximately 25 fields that show the information about the position as well as information about the person in the position. Of course, every so often a person will leave a position and someone else will be hired into the vacated position. My users would like a button on ScreenB that will, when clicked:
Copy the record information displayed in the form for just the 12 or so fields of position information being displayed on ScreenB.
Paste the information as a new record in the table.
Display the new record with the pasted information in the form.
Since the query pulls a single record, my thought was to create a new form – ScreenC – identical in all respects to ScreenB to display the new record. So, the button will copy the position information from the record displayed on ScreenB, paste it as a new record into the table, open ScreenC, jump to the end of the records in the table and display the new (last) record (which contains only the position information) on ScreenC, and close ScreenB, leaving the user with the position information only and a form that can be filled out with the employee information. This will preserve the information of the previous employee while in that position, which is required.
I’m not a trained programmer, so the code below is probably rife with errors, but it was the best I could come up with:
Dim strSQL as String
strSQL = "INSERT INTO [tblNewCurrent Emp] (numCostCenter, numPosition, txtTitles, txtClassCode. numGrade, txtPositionType, txtUnit1, txtFieldStaff, txtFedMatch, txtPositionLicReq, txtPositionOrigin, datPosAcquired, datPosLastVacated, datPosTransferred, txtOrigTitle, txtOrigClassCode, numOrigGrade, datPosReclassified) "
strSQL = strSQL & "SELECT numCostCenter, numPosition, txtTitles, txtClassCode. numGrade, txtPositionType, txtUnit1, txtFieldStaff, txtFedMatch, txtPositionLicReq, txtPositionOrigin, datPosAcquired, datPosLastVacated, datPosTransferred, txtOrigTitle, txtOrigClassCode, numOrigGrade, datPosReclassified from [tblNewCurrent Emp] "
strSQL = strSQL & "WHERE (numSystemNumber = " & Me.numSystemNumber & ")"
DoCmd.RunSQL (strSQL)
DoCmd.OpenForm frmScreenC
DoCmd.GoToRecord , , acLast
DoCmd.Close frmScreenB
The table is named “tblNewCurrent Emp”, which is why I placed it in brackets. numSystemNumber is the name of the auto-number field. All forms, queries and tables are in a single database/file. The field names in the code above are the actual names of the fields.
When I attempt to run the code, I get an error message that states, “Syntax error in INSERT INTO statement.” No other information, and no information in the Access Help system. I tried removing the brackets from the table name, and get the same error message. I would appreciate any input, thoughts, or suggestions. What is the error with the INSERT INTO statement? Is there another way to accomplish this task? Unfortunately, I can’t make structural changes to the database and since it is the backend for a number of other databases, changing the table name is not an option, either. Users access the database through the forms only. No datasheet or other views. Thanks.
EDIT: Thank you billmac1 and Remou. The "...,txtClassCode. numGrade,..." was the issue on the SQL. Once I corrected that, I used your suggestion to run the code in the Immediate Windows with the print.debug as well. Ran fine, so all that was left was to clean up the VBA code for opening and closing the forms. For anyone else attempting the same, I also set ScreenC to open to the last record in the Load property. It works perfectly now. Below is the finished code.
Dim strSQL As String
strSQL = "INSERT INTO [tblNewCurrent Emp] (numCostCenter, numPosition, txtTitles, txtClassCode, numGrade, txtPositionType, txtUnit1, txtFieldStaff, txtFedMatch, txtPositionLicReq, txtPositionOrigin, datPosAcquired, datPosLastVacated, datPosTransferred, txtOrigTitle, txtOrigClassCode, numOrigGrade, datPosReclassified) "
strSQL = strSQL & "SELECT numCostCenter, numPosition, txtTitles, txtClassCode, numGrade, txtPositionType, txtUnit1, txtFieldStaff, txtFedMatch, txtPositionLicReq, txtPositionOrigin, datPosAcquired, datPosLastVacated, datPosTransferred, txtOrigTitle, txtOrigClassCode, numOrigGrade, datPosReclassified FROM [tblNewCurrent Emp] "
strSQL = strSQL & "WHERE (numSystemNumber = " & Me.numSystemNumber & ")"
DoCmd.RunSQL (strSQL)
DoCmd.OpenForm "frmScreen C"
DoCmd.Close acForm, "frmScreen B"
Too new to this site to leave this one as a comment, but part of your SQL string caught my attention "...,txtClassCode. numGrade,...". There's a period and a space in both your field string and value string.
As Remou suggested, "...try a debug.print strSQL and paste the result into the query design window to check for problems." You might also find it beneficial to just take the SELECT portion of your statement and get it working, then try the INSERT portion.

How do I create a loop in Access VBA/SQL to select records and output to Excel?

I need some help on writing some VBA/SQL code into a module in Access, which should do the following:
Loop through Table 'Schools', with just one field (SchoolName).
Use each value in the first table to select records from Table 'ChildData', with several fields about individual children, including which school they attend (SchoolName).
For each school, export the data for its attending children into a separate Excel workbook named for that school.
Can anyone give me any starting points? Please be aware that I know very little about either VBA or SQL and am pretty much starting from scratch, therefore even the most basic explanations would be very helpful!
Thanks,
AVN
I can't see anything in your question that indicates you need anything complicated.
The first step is to create a query that joins the schools and students and when that runs, export to Excel via the menus. If that works, then you need to alter it so that you are outputting one school at a time. The "easy" way to do this would be to add to your query a parameter on School so that each time the query runs, you're displaying only one school.
Now, if you want to automate that, it becomes more complicated because the parameter will get in the way.
So, my suggestion would be to create an unbound form that has a combo box on it that displays the list of schools. You then use a reference to that combo box as criteria for your query, and use that to drive the code behind a command button:
Private Sub cmdOutputSchool_Click()
If IsNull(Me!cmbSchool) Then
MsgBox "You must first choose a school from the dropdown.", _
vbExclamation, "Choose a school"
Else
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
"qrySchoolOutput", CurrentProject.Path & "\" & Me!cmbSchool & ".xls"
End If
End Sub
Now, this doesn't automate the process, but it at least makes it easy to output each report in succession.
If you wanted it to be automated, one easy way to do that would be to bind the form to the Schools table, and bind your query to the display of the School Name on the form. Then you could have the command button walk through the records of the form and output the report for each school:
Private Sub cmdOutputSchool_Click()
With Me.RecordsetClone
.MoveFirst
Do Until .EOF
Me.Bookmark = .Bookmark
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
"qrySchoolOutput", CurrentProject.Path & "\" & Me!SchoolName & ".xls"
.MoveNext
Loop
End With
End Sub
This will output a spreadsheet for each school in the table you've bound to the form.
It would be simpler to create a query which joins the two tables on school, and then use a pivot in excel with school as the page, and use the show pages to get each school on a separate page
If you want to do it the more complicated way then in VBA you need a recordset from the schools table which shows all the schools, and a recordset from the childdata with the required fields, and a parameter against the school field.
Then in VBA you use a do loop control, which proceeds while school.EOF=false and for each school record get the childdata recordset, and put it to Excel
I would tend to do this in Excel VBA and use copyfromrecordset to put the data into Excel -simple enough to create a new sheet for each school and set the sheet name to school. You would need to add the relevant references to the VBA project - DAO or ADO - to be able to connect to the Access data.
As mentioned, you can use "" inside a string to get a quote. Example:
MsgBox "I am an ""Example""."
As for the other ,you don't really need VBA to do this. You can do it with a query:
SELECT ChildData.* INTO [Excel 8.0;HDR=YES;IMEX=2;DATABASE=C:\Example.xls].[MyWorksheet]
FROM ChildData INNER JOIN Schools ON ChildData.SchoolName = Schools.SchoolName;
You can of course do the same thing from VBA if you really want to like so:
CurrentDB.Execute "SELECT ChildData.* INTO [Excel 8.0;HDR=YES;IMEX=2;DATABASE=C:\Example.xls].[MyWorksheet] FROM ChildData INNER JOIN Schools ON ChildData.SchoolName = Schools.SchoolName;"
Still another way would be to create a select query that pulled your data and then use DoCmd.OutputTo:
DoCmd.OutputTo acOutputQuery,"MyQuery",acFormatXLS,"C:\Test.xls"
You can also use DoCmd.TransferSpreadsheet:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "MyQuery", "C:\Test.xls", True