I have a 'accdb' file and it has some queries.
Now I want use the query's output to be redirected to a text file and each of the fields are delimited by tabs.
I might have to do this multiple times over the course of the month, so I would like a button and on-clicking it it takes the queries 1 by 1 and create a new file for every query. How can I do this?
BTW the 1st row would be the field names.
Here is the code, first you have to create specification like here and replace name YourName with it's name and Query1 with your query name:
DoCmd.TransferText TransferType:=acExportFixed, _
SpecificationName:="YourName", _
TableNAme:="Query1", _
FileName:="d:\test.txt", _
HasFieldNames:=-1
You can use the TransferText method to export it as type acLinkDelim. You can write this into a bit of code behind the click event of a button or put it into a public function that takes a query name and an output path and does the rest for you
Related
I have been trying to incorporate a built in macro action (SearchForRecord) in MS Access, however cannot get it to work for the life of me. There is minimal resources available online for this operation, and I've noticed that other people have struggled with the same issue.
I made a test database just to see if I could get it to work in the most basic form. I made a table with 3 columns (ID, Name, Colour) - I turned the table into a tabular form using the Form Wizard. I created a text box with a search button.
I then made a macro operation:
SearchForRecord
Object Type: Form
Object Name (Name of the Form) "frmNewSearch"
Record: First
Where Condition: ="txtIDSearch = '" & [Forms]![frmNewSearch]![txtSearchBox] & "'"
I took the where condition syntax directly from https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/searchforrecord-macro-action
I set the button click event to the Macro that I made.
In theory, I enter the ID into the txtSearchBox and it should bring up the appropriate record within the same frmNewSearch form.
When I try this, nothing happens and it just sits on the first record. I am using MS Access 2016 - is the macro action maybe just not supported in this version?
If there is another way at approaching this it would be much appreciated!
Cheers
Referenced article states:
Note the equal sign (=) at the beginning of the expression, and the
use of single quotation marks (') on either side of the text box
reference:
="Description = '" & Forms![frmCategories]![txtDescription] & "'"
Have to actually type = sign into argument. (Yes, I hear your ranting and cursing, but that's life.)
I presume txtIDSearch is name of textbox. The criteria must use name of field, which you say is ID. If ID is number type, don't use apostrophe delimiters (apostrophe delimiters are used for text fields, # delimiter for date/time, nothing for number type). So result will show like:
Where Condition: = ="ID = " & [Forms]![frmNewSearch]![txtSearchBox]
or since code and controls are on same form, simply:
Where Condition: = ="ID = " & [txtSearchBox]
However, both fail if form is a subform. This is because form is not open independently in Forms collection. A reference incorporating parent form name fails as well. Use VBA code methods.
I am fairly new to access and I am working on a database to manage Bills of Materials (BOMs) of several products. I would like to create a form where the user can input a list of component names to see where these components are being used.
To run a query based on one word is simple but I am struggling to extend it to more than one word.
I would like the user to input the components separated by new lines like this:
Item1
Item2
Item3
...
If I use the text field as is then the query won't find anything because it takes the text field as a whole and not line by line.
I have tried to process the text field into a ListBox because I thought that it would be handled like an array but it does not have a <value> therefore it will not return any search results.
My next try was to use a second text field where I can format the information to the format "Item1";"Item2";"Item3" so that I can use it in an in statement.
If I directly put:
in ("Item1";"Item2";"Item3")
In the query criteria then it will run as expected, however if I try to reference the HelpText (which contains: "Item1";"Item2";"Item3") like so:
In ([Forms]![Search_mult_component]![HelpText])
Then I get no results. I have also tried formatting the text to include the parenthesis like so ("Item1";"Item2";"Item3")
As I mentinoed I am just getting to know Access therefore I am not sure if this is a good practice or if I am trying to force something which can be done in a simple way with a slightly different approach.
Thank you for the support in advance!
You can't. Just like table and field names, the value string of an IN statement must be present before the query runs.
Your only option is to write the SQL string dynamically and, say, create a temporary query to which you pass the SQL.
Using a list box to represent the selection criteria is a good approach as it will allow the user to select & manipulate multiple items as distinct elements, without having to worry about delimiters and such.
However, rather than attempting to access the value of the list box, I would suggest using the list box to populate an underlying table, which you can then join to the relevant field in your query, causing the results to be automatically filtered without the need for a where clause.
I have managed to solve it after #Lee Mac provided the spark!
I created a Table TempTable to store the input values and I was able to use this table in the query later. It still took some code to get there though!
In the form I used a textbox with the multiline data as defined in the question and a button to run the Query. The steps therefore are somewhat separated between the Textbox itself and the button.
The Textbox has the following code for the AfterUpdate event:
Private Sub search_text_AfterUpdate()
Dim TempTable As DAO.Recordset
Dim i As Integer
Dim allNums() As String
' ======= Open table =======
Set TempTable = CurrentDb.OpenRecordset("SELECT * FROM [TempTable]")
' ======= Clear table =======
DoCmd.SetWarnings False 'Disable warnings. If not disabled the user will be prompted to confirm the delete
DoCmd.RunSQL "DELETE * FROM TempTable" 'SQL statement used to delete all entries from a table
DoCmd.SetWarnings True 'Enable warnings
' ======= Process multiline text =======
allNums = Split(search_text.Value, vbNewLine) 'Split the multiline text
For i = LBound(allNums) To UBound(allNums) 'process line by line
If (StrComp(Trim(allNums(i)), "", vbTextCompare) > 0) Then 'Check if current text is empty string
TempTable.AddNew 'Add new Record to table
TempTable![ToSearch] = (Trim(allNums(i))) 'Fill in the text, trim whitespaces
TempTable.Update 'Update Table. Seems to be necessary for changes to take effect
End If
Next i
' ======= Clean up and close table =======
TempTable.Close 'Close the table
Set TempTable = Nothing 'No idea why this is needed :D
' ======= Refresh table =======
'DoCmd.SelectObject acTable, "TempTable"
'DoCmd.Requery
'DoCmd.GoToRecord acDataTable, "TempTable", acLast
End Sub
This code takes care of clearing the table TempTableand filling it with the new input. TempTable has two columns ID and ToSearch where ID is the primary key for the table and ToSearch will be populated with the input from the textbox. I have seen during the testing that when the entries from the table get deleted the new items will still receive new keys when added which worries me because the keys might run out at some point. This is a problem for the future but if you have any advice on this (for example removing the key from the table or sthing) then please let me know.
The code runs after the user hits an enter on the text field but needs a Requery of the table to take effect! This is included in the Button macro:
First the table oject is selected and a Requery is run. After this I close the table and open the actual Query which also needs to be requeried to show the correct updated values.
With this solution I was able to do what I intended to do without having to delve into the depths of SQL.
As always, I appreciate your comments!
I am trying to filter a subform with a textbox.
I have a query to show table records in the subform and I have the criteria to filter the table, but when I type in the textbox to filter the sub form it only shows me one record with that name. I need it to show me all the names.
The criteria for my query is below.
Like "*" & [Forms]![frmPlanningForecast]![FETextbox].[Text] & "*"
I then have an OnChange event on the textbox to requery the subform.
As mentioned above I need it to show me all the records matching what i have typed, not just one.
When I use the filter option within the table itself(Dropdown box on the field header) and select the filter from there, it works great. But I need it to be typed into a textbox.
The picture attached will show you what I mean, I have "EQ" typed in the text box but it has only returned 1 record when their are 15 called "EQ" on the table.
First of all add single quotes around Like parameter:
Like "'*" & [Forms]![frmPlanningForecast]![FETextbox] & "*'"
and second - Access has an old bug: if you refer in the query to form field like you did, it doesn't renew the value, used for criteria during Requery, you always will receive the same results. Workaround - replace reference to field by global function, which returns textbox value or use dynamic generating of RecordSource for subform.
Global function example:
Public Function GetFE() As Variable
GetFE = [Forms]![frmPlanningForecast]![FETextbox]
End Function
Place it in any standard VBA module. Then your Like will look like this:
Like "'*" & GetFE() & "*'"
I found an easier method and just wanted to let others know.
Instead of using criteria I used the following vba code.
DoCmd.ApplyFilter , (FETextbox = qryPlannedHours.LeadFE), SubFormPF
In older versions of Access, didn't there used to be an option in the query to use the sum field something like this:
[Formnane].[TextField]
I know that's very simplistic and I don't fully recall how to use it but it was something like that, simple and straight forward if you're not a VB user. Forgive my lack of conviction, I've used it before but it was 20 years ago.
I am very new to MS Access, forgive me for this simple question but I am very confused with my current problem.
So I want to run a VBA function after a table receives an update on one of its fields. What I have done is:
Create a Macro named Macro_update under CREATE->Macro, with action RunCode, and its argument is the VBA function I wish to run. The function has no bug.
Select my table, and under Table->After Update, I wrote
IF [Old].[status]=0 And [status]=1 THEN
RunDataMacro
MacroName Macro_update
But after I update my status field in my table nothing happened... I am suspicious of the fact that in step 2 my action is RunDataMacro, but I am actually running a Macro (is there a difference?)... any help is appreciated!
You can use a Data Macro to get it working locally for now. This means that the table will need to be stored in an Access database.
If your web service is not actually using the Access Runtime to interface with the access database container, then the data macros may not fire correctly nor as intended. Your mileage may vary.
If you later migrate your database to a SQL server (MySQL, Microsoft SQL, PostgreSQL) then your data macros will need to be implemented natively on the SQL server as a Trigger.
For now, I'm writing some instructions below to demonstrate how to call a VBA function from a Data Macro locally within a single Access database:
Create the VBA Function This will be the function that you want to call from the data Macro.
Create this in a Module, not in a Form or Class Module.
This has to be a function and cannot be a sub
Code:
Public Function VBAFunction(OldValue As String, NewValue As String) As String
Debug.Print "Old: " & Chr(34) & OldValue & Chr(34);
Debug.Print vbTab;
Debug.Print "New: " & Chr(34) & NewValue & Chr(34)
VBAFunction = "Worked"
End Function
Create the Data Macro (Going to be more descriptive here since people get lost here easy)
Open the Table (i.e. TestTable) in Design View
Find the correct Ribbon
In table design view, there is a contextual ribbon called Design.
On that ribbon, there is an option called Create Data Macros
Click on Create Data Macros and select After Update
The Macro Designer window should now open
Choose SetLocalVar from the Add New Action combo box
A SetLocalVar section appears.
In this section, I see Name and Expression
Set Name to an arbitrary value, such as: MyLocalVar
Set Expression to the following
Be sure to type the = sign, which will result in two equal signs being shown
Expression Text:
=VBAFunction([Old].[FieldName],[FieldName])
Save the Data Macro and Close the Macro Designer.
Save the Table and Close the Table
Test It: Create an Update Query
Next you will need to create an Update Query that performs an update on the Table that houses the Data Macro you just created.
To test this, you can just update a string field in all records to one value.
UPDATE [TestTable] SET [TestText] = "Test"
Run the query
Press Control + G to bring up the Immediate Window. You will notice that the Data Macro fired for every updated record.
I have a form which has a combobox and a button. When a value is selected in it, I have to retrieve the value selected in combo box and based on that value run a query. The query produces a table of 5 columns. I want this table to be exported to Excel Sheet. Please help me out.
As Tom said, you can use the Docmd.TransferSpreadsheet command. First you need to have your query set to be a parameterized query that references your combobox. I'm assuming it's part of your WHERE clause. So, your query may look like:
SELECT * FROM yourTable WHERE values = [Forms]![yourForm]![yourComboBox];
Assuming your query you just wrote is named "qryExport", You'll put this code into a button on your form on the on click event:
DoCmd.TransferSpreadsheet acExport, , "qryExport", "C:\yourPath\exportedReport.xlsm", True
You should then be able to go in the path you specified and open that excel file and make sure everything worked.
Hope this helps.
OK, simple enough. You'll have to use VBA.
On the click event of the button, you'll just have to execute a DoCmd.TransferSpreadsheet command. There's several options so you can just look it up here.
For the table name, use a query instead that includes a reference to your ComboBox. I.e. =[Forms]![FormName]![ControlName]