Access 2002 VBA: Creating an incremented Item Code - ms-access

Ok, here's the deal. I have a previously existing SQL Server 2008 database linked to an Access 2002 database via linked tables/views. Up until now, the item code has been a nvarchar type.
I have a SQL query which casts the item codes as Int and an Access 2002 linked query that uses the MAX() function to give me the highest value. It is from this highest value I wish to start incrementing the item codes by 1 every time the "New" record button is selected.
Right now, when "New" is selected, the form is blank, waiting for input. What I want to do is, when "New" is selected, to have the value of the MAX() function query passed to a variable, have 1 added to it, and the resulting value placed in the "Item Code" text box.
It sounds easy enough, but for some reason I can't seem to get it to work. I know Access fairly well, but my VBA is fairly weak.

Sound like it could be done with a custom function.
Dim rs as dao.recordset
Dim db as dao.database
Dim NextInt as string
set db = currentDb
set rs = db.openrecordset(YourMaxQuery,dbOpenSnapshot,dbSeeChanges)
if rs.recordCount >0 THEN
NextInt = Cstr(rs!MaxValue + 1)
END
set rs = nothing
set db = nothing
return NextInt
Call the function in the update statement of your query and it should give you the value you're looking for.

Sorry I took so long to get back to this thread.
Ok, I ended up going with a GlobalSequence in MS SQL Server 2008. Basically just created a table with the max id value as a seed, and matched it with a column that has a bit value to prevent rollbacks and duplicate item codes should a record get deleted. After that, it was pretty easy. :)

Related

Access VBA Search Loop

I am currently making an search loop in VBA for my database. In this database I Have 2 Tables, one with the customers records called Main and another one with search words called Sparr. The idea is to use a filter to filter out the customers that match any of the search words in the Sparr table. Any customer that does not match any of the search words gets added to another table called filteredCustomerT.
For example:
table "Main"
Field "Mail"
mike#coolmail.com
john#hotmail.com
dave#mail.com
jonny#mailx.com
table "Sparr"
Field "sparrord"
hotmail
jonny
table "Testtable"
Field "testMail"
mike#coolmail.com
dave#mail.com
So if I run this VBA code I want john#hotmail.com and jonny#mailx.com to be filtered out. The Main table contains 200k records and the Sparr table contains 2k search words. I have wrote some VBA code that should loop through the Main table. For every record in the Main table a have another nested loop that loops through the Sparr table so see if there is any match. If there is not a match the VBA code copies the entry to anther table called Testtable. I Use the inStr function to do the matching.
Below I have posted the VBA code that does not seem to work. Can anyone help me ant maybe point out a fault in the code. I am very new to VBA programming.
Option Compare Database
Option Explicit
Sub filter()
Dim mainMail As Recordset
Dim sparrSokord As Recordset
Dim testtableTestmail As Recordset
Dim mainTemp As String
Dim sparrTemp As String
Dim match As Integer
Set mainMail = CurrentDb.OpenRecordset("Main")
Set sparrSokord = CurrentDb.OpenRecordset("Sparr")
Set testtableTestmail = CurrentDb.OpenRecordset("Testtable")
Do Until mainMail.EOF
mainTemp = mainMail![Mail]
match = 0
sparrSokord.MoveFirst
Do Until sparrSokord.EOF
sparrTemp = sparrSokord![sparrord]
If (InStr(mainTemp, sparrTemp) <> 0) Then
match = 1
Exit Do
End If
sparrSokord.MoveNext
Loop
If (match = 0) Then
testtableTestmail.AddNew
testtableTestmail![testMail] = mainTemp
testtableTestmail.Update
End If
mainMail.MoveNext
Loop
End Sub
InStr can operate in unexpected ways is you have nulls/empty strings/etc, involved.
I've noticed that you have nothing resetting the position of SearchwordWord back to the beginning of the record set once you reach the end.
Naturally you would do something like SearchwordWord.MoveFirst before the Do Until SearchwordWord.EOF. It doesn't hurt to do one before the Do Until customerMail.EOF either
I'll also note the Do Until always executes the contents of the loop, and then checks the condition at the end (which could be giving you unexpected results, especially with SearchwordWord being at EOF after the first successful pass of the loop.
You probably want to use a while/wend instead for both do untils (I practically never use them as it is). This is probably the biggest cause of your grief.
The problem is now solved. I just had to close some programs and try again with the updated code above. Worked just fine!

Error 3061 Query "loses" form text value

I looked at a number of 3061 posts but they all have the query in VB. I am trying to run an already saved query in Access, that has a filter using a text field on a form. So all I am trying to do is just get a recordset from an existing query.
Not sure quite how to explain what's going on. But I have a Master form which holds the current selected date in a text object. I have a query that filters results based on the text object value:
SELECT DISTINCT EmployeeName
FROM dbo_Audits
WHERE dbo_Audits.AuditDate = [Forms]![MasterForm]![ReportDate]
Running the query is fine and it pulls for the selected date except in a specific circumstance.
If I open a subform, and keep the master form still open but not in focus, it still works i.e. I can run the query and it pulls the list of employees that had an audit that day.
But if I click a button on the subform to perform an action and put a breakpoint on the OnClick event, then try to run the query, it doesn't return any results. Its because it doesn't "recognize" or it's lost the value of "[Forms]![MasterForm]![ReportDate]" and therefore no results are returned.
Odd thing is, at the breakpoint, I query the text box value in the intermediate window and it still returns the date.
That is one way I have tested it. But what I am really trying to do is get the recordset from this query, in the back end coding, but when it encounters this coding:
strSQL = "SELECT * FROM " & strQueryName & " "
Set rstNames = CurrentDb.OpenRecordset(strSQL)
The OpenRecordSet returns the error message:
3061 - Too Few Parameters. Expected 1.
I put a breakpoint on the OpenRecordSet and do a DCount on the strQueryName and get a result of the number of records. So the query is kind of working. But not when I run the query through access (while on the breakpoint) and not when it tries to open the recordset.
Any ideas what's going on and how to fix this?
Since OpenRecordset does not dereference [Forms]![MasterForm]![ReportDate], and thinks it's a parameter, open the the saved query as a QueryDef object and give it the parameter value Access wants. Then you can use OpenRecordset from the QueryDef.
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs(strQueryName)
qdf.Parameters(0).Value = Eval(qdf.Parameters(0).Name)
Set rstNames = qdf.OpenRecordset()

Creating a recordset in Access with VBA

From the title, i know it seems like this has been answered too many times over, but I have a series of incomprehensible problems with it. This is also my first time asking for help through posts, so I might forget to mention some stuff.
Function update_location_id()
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL As String
Set db = CurrentDb
strSQL = "select id from location"
Set rs = db.OpenRecordset(strSQL)
MsgBox (rs.RecordCount)
End Function
I removed almost all the code from this function just to try to figure out why i couldn't get a record. this code generates a "too few parameters. expected one on the 'set rs = ...' line.
However if i change the select query's id to *, it works fine. However it returns 1. This is somewhat confusing seeing as there are a total of 3 records in the locations table right now.
Just incase its needed the location table looks like
id description
1 "Location 1"
2 "Location 2"
3 "Location 3"
This is causing me to pull my hairs out and i can't really move on with my project if i can't do such a basic database action as...getting information from it.
References: Visual Basic for Applications, Microsoft Access 14.0 Object Library, OLE Automation, Microsoft Office 14.0 Access database engine object, Microsoft Internet Controls.
Typically, the error "too few parameters" comes up when you use a column name that does not exist in the table, so it is interpreted as a parameter.
So, despite your given table data, I'd really check again the table name (location) and the column name (id).
As for the "1", yes, you have to insert
rs.MoveLast
rs.MoveFirst
after opening the recordset to get the correct RecordCount. Before moving to the last one, the recordset does not know how many records it yields (there are some more details to this problem, which I don't remember exactly right now, concerning recordset-type or so).

Autonumber not working correctly

I am trying to read the last row with a value in the Number column and then increase it by one. For some reason the code below is reading the second row in the table not the last? Any ideas why?
Dim dvProjectName As DataView = DirectCast(AccessDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
Dim strProjectName As String = DirectCast(dvProjectName.Table.Rows(0)("Number"), Integer)
Autonumber fields are handled by the MS Jet database engine directly. Attempting to change the value yourself will usually result in an error. If you want to manipulate the values yourself - change the field to a number field and use VBA code to change the number. Else, prepare to be disappointed as Jet won't let you change the numbers.

getting minimum value in a recordset field without Looping

I am using Access 2007 and writing a macro in VBA.
"Analyze" subroutine is passed a recordset rev_rec. This recordset has two fields "PeriodNo" (Integer) and "Revenue"(double).
Minrev is a variable where I have to store the minimum value of "Revenue" field. The code that I am using is below.
Public Sub Analyze(rev_rec As DAO.Recordset)
Dim Minrev As Double
rev_rec.MoveFirst
Minrev = rev_rec("Revenue")
While Not rev_rec.EOF
If rev_rec("Revenue") < Minrev Then
Minrev = rev_rec("Revenue")
End If
rev_rec.MoveNext
Wend
rev_rec.MoveFirst
.
.
.
End Sub
I tried using DMin() with recordset but am not able to find a way to do that. Is there a way to do this without using any kind of loop?
I think your best bet is to build a new recordset using a SQL statement that only retrieves one record, the one with the minimum for the desired period. Another option is, you could open this particular recordset with the Order By on the Revenue column Ascending. This way you would know that the smallest value will be in the first record.
Andy Brown's suggestion of using DMin should also work. It's actually an idea very similar to my first suggestion.
The problem is that you're passing a recordset. If you just had the table or query name (or SQL statement), you could just use DMIN. Eg:
MinRev = DMIN("Revenue","TableOrQueryNameInQuotes","")
The third argument can be used to set some criteria. For example:
MinRev = DMIN("Revenue","TableOrQueryNameInQuotes","PeriodNo > 5")
Be warned, however, that the functions starting with D (DMIN, DLOOKUP, DSUM) run very slowly, although if you've got less than about 10,000 records you won't notice this.