Export dynamic fields from Access to csv (schema.ini?) - vba

I'm trying to export a crosstab query from Access 2010 to a csv without a text qualifier. I'm able to use the Transfer Text method with my other exports; the trick with this one is that the number of fields (and their names) change depending on what the user selects on the form, but the setup in the SpecificationName is static. If I don't indicate a SpecificationName, I can get whatever fields are run in the query as appropriate, but I get quotes around my text fields, which I don't want. If I set up a specification to set the text qualifier as None, I'm stuck with a set list of fields. I tried sticking an asterisk in the FieldName area when setting up the specification, but got
The number of fields in your export specification does not match the number in the table you have chosen to export.
I'd really like some kind of "SELECT *" in there, but it doesn't look like it's possible?
Poking around, it looks like I might need to set up a schema.ini? Of course, this would need to be dynamic as well. I found a resource that was written for Access 97: https://support2.microsoft.com/default.aspx?scid=kb;en-us;155512, but it doesn't seem to work in Access 2010. Even after updating db As Database to db As DAO.Database, I get
Expected variable or procedure, not module
When running the following in the Immediate window (with appropriate text subbed in):
?CreateSchemaFile(True,"C:\MyFilepath","ExportFileName.txt","qryCrosstabs")
I've reached the limits of my (limited) VBA chops to figure this out. Writing a script for a dynamic schema.ini seems like overkill for just wanting to get rid of quotes, but if that's what has to happen, any pointers in the right direction would be excellent.
Thanks!

Ah, ok, I figured it out. I thought I had to specify the columns in Schema.ini, but I was mistaken. I just needed to set the header to true; that way it'll read whatever happens to end up in the query. Setting the text delimiter to none was also a key piece.
Here's all I needed in Schema.ini (just needs to be in the same directory as the exported file):
[ExportFileName.txt]
Format=CSVDelimited
ColNameHeader=True
TextDelimiter="none"
And the code:
Private Sub cmdExport_Click()
Dim dbs As DAO.Database
Set dbs = CurrentDb
dbs.Execute "SELECT * INTO [text;database=C:\filepath].[ExportFileName.txt] FROM qryCrosstabs"
While this ultimately works, having an external Schema.ini file is clunkier than I'd like. I've seen a few places where adding extended properties to the dbs.Execute line will indicate csv (FMT=Delimited) and column headers (HDR=Yes). Having one for text delimiters would be the most parsimonious solution, but from what I can tell, that doesn't exist. I'm happy to be corrected on that if it does, though!

Related

Replacing a DECLARE in an SQL command with a cell value [duplicate]

I "linked" Excel to Sql and it worked fine - I wrote some SQL script and it worked great. All I want to do is to pass parameter to query. Like every time I make refresh I want to be able to pass parameter (filter condition) to Sql Query.
In "Connection Properties" Parameters button is disabled. So I can't make parameter query.
Can Anyone help me?
This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.
This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.
So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.
Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))
What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.
First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:
Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.
Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).
Sub RefreshQuery()
Dim queryPreText As String
Dim queryPostText As String
Dim valueToFilter As String
Dim paramPosition As Integer
valueToFilter = "DB_TABLE_NAME.Field_Name ="
With ActiveWorkbook.Connections("Connection name").OLEDBConnection
queryPreText = .CommandText
paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
queryPreText = Left(queryPreText, paramPosition)
queryPostText = .CommandText
queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
.CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
End With
ActiveWorkbook.Connections("Connection name").Refresh
End Sub
Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).
Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).
Save and close the VBA editor.
Enter your parameter in the appropriate cell.
Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!
Notes:
Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous.
If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".
This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.
It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)
The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.
When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.
When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.
I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.

MS Word VB make check box control invisible when merge field is null

I have a query that pulls information I need to use in a mail merge document to email to people for verification of information. There are 8 fields they need to verify, preferably with a check box control, but some of the fields contain no information. I would like to make the check box next to merge fields that contain no data (or whatever I may need to write into the query to make this work) invisible. If this could be accomplished easier in a completely different way, that would be fine too. Thank you.
As Cindy said, this kind of thing is handled via field coding in the mailmerge main document, not via VB code. Such a field might be coded as:
{IF{MERGEFIELD myCheck}<> "" "[ ]"}
or:
{IF«myCheck»<> "" "[ ]"}
where 'myCheck' is the field name and '[ ]' is the checkbox content control.
Note: The field brace pairs (i.e. '{ }') for the above examples are all created in the document itself, via Ctrl-F9 (Cmd-F9 on a Mac or, if you’re using a laptop, you might need to use Ctrl-Fn-F9); you can't simply type them or copy & paste them from this message. Nor is it practical to add them via any of the standard Word dialogues. Likewise, the chevrons (i.e. '« »') are part of the actual mergefields - which you can insert from the 'Insert Merge Field' dropdown (i.e. you can't type or copy & paste them from this message, either). The spaces represented in the field constructions are all required.

MS Access: Query to list number of files in a series of folders

I have folders labeled by their keyfield, so 1, 2, ... 999, 1000. located in currentproject.path\RecordFiles\KeyFieldHere so like currentproject.path\RecordFiles\917.
I want to run a query that will count how many files are in each folder. I know this can be done with the DIR function through visual basic, but I can't seem to run it through a SQL query.
I've tried using this function in a SQL equation, so Expr1: [FlrFileCount("Y:\Education\Databases\RecordFiles\")] as one of the fields just to see if it can work, but it prompts me for a value and then returns nothing.
EDIT: I tried an approach using the FlrFileCount function in a continuous form, and it does work, BUT... I get an error after every single line. I have a field in a continuous form of =FlrFileCount([currentproject].[path] & "\recordfiles\" & [ID]), but when I run the form I get an error "Error 76, Error source: FlrFileCount, Error description: Path not found." Which is crazy because IT WORKS, it properly lists the number of files in the folder for each record.
I just need to get this functionality over into a SQL query so I can pull that data for mail merges.
I currently have something similar in a form. The form has an onload property to run a module (Link here) to create a list of all the files in the relevant folder to that record, and then I have another field that just counts the number of entries in the list. However a list can't be a value in a SQL query, so I don't think that code will help.
Thanks to Tim Williams, the answer was to put
=FlrFileCount(Currentproject.Path & "\recordfiles\" & [ID])
It seems the [currentproject].[path] part was where the error was. What's confusing is that in other places, MS Access adds the extra [] around currentproject and path, and I don't know why.
Thank you so much for your help! Now to the tricky part: Implementing a proper naming scheme by program ID across a sharepoint so that the relevant folder can be opened consistently even when program names change.

Applescript in reverse?

& thanks for all the tips i've had here... this site is ace!
My question is, basically, how to correctly write my script. I've written an applescript, that works great for 1 variable, but i'll need to add hundreds of variables, and that'll currently mean adding hundreds of "if" statements.
So my script queries a FileMaker database & receives an input field (which is variable), i then want to open a the related textEdit file & read the text.
ie... FileMaker Pro returns "123", so i want to open textEdit file "123".
However, my script currently says If text returned is "123" then do this, else if text returned is "234" do this, else if text returned is "345" do this. To write this script with hundreds of "Ifs" doesn't make sense, but i can't get my head around swapping my script to say - returned value is "123" so use file 123.
Does anyone have a suggestion?
Thanks

how to pass parameters to query in SQL (Excel)

I "linked" Excel to Sql and it worked fine - I wrote some SQL script and it worked great. All I want to do is to pass parameter to query. Like every time I make refresh I want to be able to pass parameter (filter condition) to Sql Query.
In "Connection Properties" Parameters button is disabled. So I can't make parameter query.
Can Anyone help me?
This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.
This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.
So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.
Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))
What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.
First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:
Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.
Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).
Sub RefreshQuery()
Dim queryPreText As String
Dim queryPostText As String
Dim valueToFilter As String
Dim paramPosition As Integer
valueToFilter = "DB_TABLE_NAME.Field_Name ="
With ActiveWorkbook.Connections("Connection name").OLEDBConnection
queryPreText = .CommandText
paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
queryPreText = Left(queryPreText, paramPosition)
queryPostText = .CommandText
queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
.CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
End With
ActiveWorkbook.Connections("Connection name").Refresh
End Sub
Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).
Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).
Save and close the VBA editor.
Enter your parameter in the appropriate cell.
Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!
Notes:
Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous.
If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".
This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.
It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)
The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.
When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.
When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.
I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.