add variable field value to output file name - export-to-excel

I have a db that imports files in to temp tables prior to exporting the data to excel and appending the temp data to the main table. Each of the files loaded to the temp tables had a column with the same unique value for each record. I would like to create a query to used to filter on the first and add that value from the query to my file naming convention for the person that has to work the output files.
I've created the query that filters on the first but I am not able to find a way to incorporate that result into the file naming for the output.
Function Export_2nd_Level_Excel()
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "2ndLevel", "\pbfsvr01\pbf\PharmNetwork\Audits_Pharmacy\Provider_Audits\Completed Audit files\2nd_Level\" & "[Insert NPI]" & Format(Now, "_ddmmmyy""_2ndLevel_to_PharmAudit") & ".xlsx", True
End Function
I would like to have the "[Insert NPI]" be the actual value from the query that pulls the first of NPI.

after playing around with this for quite some time, I was able to make this work
Function Export_2nd_Level_Excel()
Set db = CurrentDb
Set recd = db.OpenRecordset("2nd_level_NPI")
Dim NPI As String
recd.MoveFirst
NPI = recd![NPI]
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "2ndLevel", "\pbfsvr01\pbf\PharmNetwork\Audits_Pharmacy\Provider_Audits\Completed Audit files\2nd_Level\" & NPI & Format(Now, "_ddmmmyy""_2ndLevel_to_PharmAudit") & ".xlsx", True
End Function

Related

How to use a variable for the criteria in a query to restrict the query to the active form?

I have form named "frmBond-MuniDetailsAE". It has a combo box named "cboStep". The Row Source for cboSteps is an embedded query that retrieves records from a table named "tblBond-Steps", and it has as Criteria -
[Forms]![frmBond-MuniDetailsAE]![SYM]. This restricts the query to records in tblBond-Steps to only those that have a SYM field that matches that field in the form. This works fine. But I would like to be able to copy and reuse the form for other types of bonds, and I don't want to have to rewrite the embedded query in each copied form. So I wanted to use a variable in the query criteria that would reference the current form.
Following answers given in StackOverflow at How do I reference the current form in an expression in Microsoft Access?, I wrote a Public Function named "FormName()". Here is the function:
Public Function FormName() As String
Dim frmCurrentForm As Form
Set frmCurrentForm = Screen.ActiveForm
FormName = "[Form]![" & frmCurrentForm.Name & "]" & "![SYM]"
End Function
Then in the embedded query for the combo box, I entered "FormName()" as the criteria. Here is the SQL for that query:
SELECT [tblBond-Steps].SYM, [StepDate] & " # " & [Cpn] AS Steps, Format([tblBond-Steps].
[StepCpn],"0.0000%") AS Cpn, [tblBond-Steps].StepDate
FROM [tblBond-Steps]
WHERE ((([tblBond-Steps].SYM)=FormName()))
ORDER BY [tblBond-Steps].StepDate;
But when I open the form with the above query as the Row Source for cboSteps, I get VBA Run-time error '2475': "You entered an expression that requires a form to be the active window."
I can't figure out what I'm doing wrong. Can someone help me?
You must return the value, not the expression:
Public Function FormName() As String
Dim frmCurrentForm As Form
Set frmCurrentForm = Screen.ActiveForm
FormName = frmCurrentForm![SYM].Value
End Function

Loop to run a series of queries to append a table for each record in a different table. MS Access 2010

Here is what I need to do:
I have a series of queries that I use to create a final report with multiple columns of statistics for an item. I have a table set up with a key for each item. What I need to do is create a loop that runs the series of queries for an item and uses the final query to append the results to "report" table.
I have all of the Make Table queries set up and the final Append query. There are two queries that require the key, the rest of the queries are dependant on the results of the first two. So, I need to use that key as a parameter in those two queries. What I need is a loop that will for each key in the "Items" table run the queries on that key, then loop.
I have a module setup to run the complete set of queries, but right now I need to run it for each item. My thinking is that I need a "for i in items..." type loop, but I do not know how to do that in VBA
Using MS Access 2010
As far as I understand you want to run multiple queries where queries are saved in a table. Some of the queries depends on parent query.
pseudo logic:
Run and Execute Parent Query
If result exists retrieve value
Start loop until parent query has values
Retrieve/construct sub queries
Execute sub query
End loop
some pseudo code:
dim MyDb as Dao.Database
dim myRs as Dao.Recordset
set mydb = currentdb
dim SQL_PARENT as string
sql_parent = "" ' Retrieve your parent query here
sql_parent = vba.replace(sql_parent, "searchkey", "replace_key") ' Replace keys
' or if you have the keys in a table then use the dlookup() function to replace keys
set myrs = mydb.openRecordSet(sql_parent)
'do error trapping here
dim iResult = nz(myrs("ResultField"),"")
'follow the parent query operation
'construct the sub queries
dim RS_SUB as DAo.Recordset
dim SQL_SUB as string
dim I as integer
for i = 1 to total of your query collection
sql_sub = query_collection(i)
sql_sub = vba.replace(sql_sub,"searchkey",iResult)
set rs_sub = mydb.openrecordset(sql_sub)
next i
note: this is just a pseudo answer to help you to understand the possibilities to your scenario.

Query Disconnected RecordSet

Background: a LOB app we use has the ability to use macros written in VBScript, but no access to WScript, etc., as far as I know.
I have successfully received user input, passed it to a stored procedure on a SQL Server, and returned a recordset to the VBScript macro in the application.
What I want to do now, is write a function or loop or something, that for as long as there is a record left in the recordset, accept additional user input, and check this against the returned recordset.
The recordset returned from SQL Server contains two columns: PART_ID and PART_QTY. For as many number of entries there are, I want to accept additional user input, lets say PART_ID_INPUT and PART_QTY_INPUT, and validate it against the in-memory recordset.
My biggest problem is working with the disconnected recordset.
When in doubt, read the documentation. You can use the Filter and RecordCount properties to determine if the recordset contains matching records:
part_id_input = InputBox("Enter part ID:")
If part_id_input <> "" Then
rs.Filter = "PART_ID = '" & part_id_input & "'"
If rs.RecordCount > 0 Then WScript.Echo "Found matching record."
End If
The filter is cleared by setting it to an empty string:
rs.Filter = ""
The current record can be removed from the recordset using the Delete method:
rs.Delete
Navigate through records via MoveFirst/MoveLast/MoveNext/MovePrevious.

"Query is not understandable" - Full text searching where field types have changed

A client have a long lived IBM Notes application where someone along the line changed the type of a field from number to text.
So, now when we're trying to do an FT search like: [myField] = "1234" receive the error message: "Query is not understandable".
If I do: [myField] = 1234 it works but won't return any hits. Even though there's a document where myField = "1234".
The field is of type text in the design.
I've created a new view for testing, only allowing documents from one form.
Deleted the full text index (even on the file system)
updall -X
Fixup -r
Created full text index
In my test view I've got one column that shows if the field content being searched is of type text #IsText(myField) and all rows shows: 1 (so it's field content must be text)
None of the above worked so I created a new database copy locally.
Same problem.
Created an entirely new database (for testing only), form, view and full text index and that works.
Feels like the existing database design somewhere stores the old field type...
Any ideas appreciated.
Thanks!
/J
Datatypes and field names are stored in the UNK table. There is just one entry per field name, so it's critical not to use the same field name more than once in an application with different datatypes.
You need to rebuild the UNK table, as I blogged here http://www.intec.co.uk/full-text-search-musings/
Note, it must be an offline compact, as Duffbert says here http://www.duffbert.com/duffbert/blog.nsf/d6plinks/TDUF-5SMHV4. If anyone is in the database when you do the compact, it will fail and the UNK table will not be rebuilt.
Links are useful, but if you don't want to remove data from documents - for me such steps worked (and there was no need in removing fields from forms in designer):
Run from designer with manager access with such code inside
Sub Initialize
Dim s As New NotesSession
Dim db As NotesDatabase
Dim dc As NotesDocumentCollection
Dim doc As NotesDocument
Dim i As Integer
Dim nc As NotesNoteCollection
Dim noteid As String
Dim nextnoteid As string
Dim itemArr As Variant
Dim NeedSave As Boolean
Const ITEM_NAME = "itemName1|itemName2"
itemArr = Split( ITEM_NAME, "|" )
'погромист-кун не должен забывать про наличие итемов в формах...
Set db = s.Currentdatabase
Set nc = db.CreateNoteCollection(False)
nc.SelectForms = true
Call nc.BuildCollection
noteid = nc.Getfirstnoteid()
For i = 1 To nc.Count
Set doc = db.Getdocumentbyid( noteid )
noteid = nc.Getnextnoteid( noteid )
NeedSave = false
ForAll IA In itemArr
If doc.Hasitem( IA ) Then
Call doc.Removeitem( IA )
NeedSave = true
End If
End ForAll
If NeedSave Then
Call doc.Save( True, False )
End If
Print CStr( i ) & "\" & CStr( nc.Count )
Next
End Sub
Remove database index
Run from administrator command lo compact database.nsf -c , like mentioned in links above
Create index

How can I use Linq with Dataset.xsd files?

How can I use Linq with Dataset.xsd files?
I've looked at Linq-to-Datasets and Linq-to-XSD but they don't really seem to work directly with the Visual Studio DataSet.xsd files.
EDIT: I actually found a great link for this: link text but I can't seem to figure out what to do if I want to query on related tables.
Dim taFields As New TestDSTableAdapters.FieldTableAdapter()
Dim fields = taFields.GetData()
Dim results = From f In fields Select f
For Each field In results
Response.Write(field.FieldID & " " & field.Label & " " & field.FieldTypeRow.FieldTypeLabel)
Next
I get an "Object reference not set to an instance of an object." error when running the above code because, I guess, field.FieldTypeRow.FieldTypeLabel isn't actually part of the query of data. Do I have to create a method that returns data from that data also? I'm assuming this would be the case (that taFields.GetData has to return all the FieldType data results too if I'm going to reference it - in Linq to SQL it does all this for me so it's a little disappointing)
A DataSet is just a container for your data, so you need to fill it first. LINQ to SQL will create SQL and go to the database for you...but when you're working with DataSets, you're using LINQ to Objects, which won't create SQL. So you need to make sure that all tables you need in the DataSet are filled before you start writing LINQ to query your DataSet.
I think you're looking for something along these lines:
Dim taFields As New TestDSTableAdapters.FieldTableAdapter()
Dim taFieldTypes As New TestDSTableAdapters.FieldTypesTableAdapter()
Dim ds As New TestDS
taFields.Fill(ds.Fields)
taFieldTypes.Fill(ds.FieldTypes)
Dim results = From f In ds.Fields Select f
For Each field In results
Response.Write( _
field.FieldID & " " & field.Label & " " &
field.FieldTypeRow.FieldTypeLabel)
Next
Dim taFields As New TestDSTableAdapters.FieldTableAdapter()
Dim fields as TestDSTableAdapters.FieldsDataTable = taFields.GetData()
Dim results = From f In fields Select f
For Each field In results
Response.Write(field.FieldID & " " & field.Label & " " & field.FieldTypeRow.FieldTypeLabel)
Next
You forgot to set the type for fields. That is why yo uwere getting object reference problems. You do not have to create a new blank dataset.

Resources