Dlookup Function in MS Access 2007 vba - ms-access

I have a textbox that has a name ISCO68Code and ISCO68Title both are texts.
When I encode in ISCO68Code, a caption must appear on ISCO68Title that corresponds in my other table, libISCO1968.
Below is my Code Builder:
Private Sub ISCO68Code_AfterUpdate()
ISCO68Title = DLookup("ISCO68Code", "libISCO1968", "[ISCO68Code]=" & ISCO68Code&)
End Sub
Sadly, I got an error message:
Compile error: Type-declaration character does not match declared data
type.
Any help will do.

You need the quotes telling that the variable is text:
Private Sub ISCO68Code_AfterUpdate()
ISCO68Title = Nz(DLookup("ISCO68Code", "libISCO1968", "[ISCO68Code]='" & ISCO68Code & "'"))
' If the control is a Label, set its Caption:
' ISCO68Title.Caption = Nz(DLookup("ISCO68Code", "libISCO1968", "[ISCO68Code]='" & ISCO68Code & "'"))
End Sub
But your function doesn't make much sense, as DLookup will return the same ISCO68Code as you look up ... except if you just will check if it exists.

Try this function :
Private Function ISCO68Code_AfterUpdate(ByVal ISCO68Code As String) As Variant
ISCO68Code_AfterUpdate = DLookup("ISCO68Code", "libISCO1968", "[ISCO68Code] = " & ISCO68Code)
End Function
Private Sub ISCO68Code_AfterUpdate_test()
Dim ISCO68Title As Variant
ISCO68Title = ISCO68Code_AfterUpdate(ISCO68Code)
'MsgBox ISCO68Title
Debug.Print ISCO68Title
End Sub

Related

How do I use a variable from a different function in another function?

I have one method
Public CurrentFileNameNoExtension As String
Public Sub importexcelfile()
CurrentFileNameNoExtension ="Filename"
'do something
End Sub
I want to use CurrentFileNameNoExtension value in onEnter event of the dropdown list(cmvalues) event. That Value use in sql query. My code is
Private Sub cmvalues_Enter()
Dim qstng As String
qstng = CurrentFileNameNoExtension
Me.cmvalues.RowSourceType = "Table/Query"
Me.cmvalues.RowSource = "Select F1 from " & qstng & " WHERE F1 <> 'Control Model';"
End Sub
But qstng value is empty. it is not giving the value in the importexcelfile() function.
EDIT: As I've just noticed, thanks to #simoco, that this is indeed for a userform, there are actually a couple of things to pull this off. One is using globals, which is quite tricky, and another is to use a function to get the string you want.
Function CurrentFileNameNoExtension() As String
'Do some FSO or GetOpenFileName here.
CurrentFileNameNoExtension = "Filename"
End Sub
Private Sub cmvalues_Enter()
qstng = CurrentFileNameNoExtension
Me.cmvalues.RowSourceType = "Table/Query"
Me.cmvalues.RowSource = "Select F1 from " & strFileName & " WHERE F1 <> 'Control Model';"
End Sub
There is not much of an issue using the code you have, really. You just have to make sure that the first sub is called before the second one so that cmvalues_Enter has a valid string to process.
Place this function under Microsoft Access Class Objects Form control,Where cmvalues dropdown exists
Public CurrentFileNameNoExtension As String
Public Sub importexcelfile()
CurrentFileNameNoExtension ="Filename"
'do something
End Sub

DAO access recordset not updating

I have an access report that updates 4 image controls based on a table that is sourcing images from a directory. The report generates a page per record, however the image controls are not changing after page 1 (just showing same images for all the other pages). Appartently, the code worked fine on Windows XP and now does not work on Windows 7 OS (both used Office 07). Here is the code:
Private Sub Report_Current()
UpdateImages
End Sub
Private Sub Report_Load()
UpdateImages
End Sub
Private Sub Report_Page()
UpdateImages
End Sub
Private Sub UpdateImages()
On Error GoTo errHandler
Dim RS As DAO.Recordset
Set RS = CurrentDb.OpenRecordset("SELECT Image_Loc, Image_Name FROM HH_Media WHERE InspectionID = " & CInt(Me.InspectionID.Value) & " ORDER BY MediaID ASC")
If Not RS.BOF And Not RS.EOF Then
Dim i As Integer
For i = 1 To 4
If Not RS.EOF Then
Dim pictureCtrl As Image
Set pictureCtrl = GetControl("Image" & i)
Dim strImage As String
strImage = RS.Fields("Image_Loc").Value & "\" & RS.Fields("Image_Name").Value
If Not pictureCtrl Is Nothing Then
If FileExists(strImage) Then
pictureCtrl.Picture = strImage
SetLabel "lblImage" & i, RS.Fields("Image_Name").Value
Else
pictureCtrl.Picture = ""
SetLabel "lblImage" & i, "Does not exist"
End If
End If
RS.MoveNext
Else
Exit For
End If
Next
End If
RS.Close
Set RS = Nothing
Exit Sub
errHandler:
MsgBox "An error occurred while updating the form display." & vbNewLine & Err.Description, vbApplicationModal + vbCritical + vbDefaultButton1 + vbOKOnly, Me.Name
Resume Next
End Sub
The images do exist in the directory that are referenced in the table. Any ideas of what is missing?
Thank You
Whenever I need to do some dynamic content I always use the [section]_Format event - so if your controls are on the Detail section then:
Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
If FormatCount = 1 then 'only need to do this once per record
UpdateImages
Endif
End Sub
I've never seen the GetControl method, and I don't have a lot of experience using the Image control, but it seems like that the Dim statement should read more like:
Dim pictureCtrl as Control
Set pictureCtrl = Me.Controls("Image" & i)
I would insert a break and verify that
strImage = RS.Fields("Image_Loc").Value & "\" & RS.Fields("Image_Name").Value
is returning values you expect. You can also shorten these to:
strImage = rs!Image_Loc & "\" & rs!Image_Name
sometimes Access doesn't like the added ".value" as this is already the default return.

Cannot pull value from user defined function in Access 2007

I have created this function GetSubName that I need to return the name that is saves from a pull down box. It does this just fine as the dialog boxes I have used shows that it sets the variable correctly. The problem is that when the SQL below runs in a query I get the error: "Undefined function 'GetSubName' in expression." I am new to VBA so any help would be much appreciated.
Here is the code:
Option Compare Database
Option Explicit
Private stSubName As String
Private Sub Command2_Click()
On Error GoTo Err_Command2_Click
Dim stDocName As String
Dim stSubName As String
SubcontractorCombo.SetFocus
stSubName = SubcontractorCombo.SelText
'Confirm that stSubName variable is holding correct value'
MsgBox "Name of Subcontractor Selected is " & stSubName
SetSubName stSubName
GetSubName
DoCmd.Close
stDocName = "Summary Asphalt Production for Subcontractor"
DoCmd.OpenQuery stDocName
Exit_Command2_Click:
Exit Sub
Err_Command2_Click:
MsgBox Err.Description
Resume Exit_Command2_Click
End Sub
Public Sub SetSubName(Value As String)
'Set the module variable to be the value passed in from externally'
stSubName = Value
End Sub
Public Function GetSubName() As String
'Returns the value of the module variable'
GetSubName = stSubName
'MsgBox "GetSubName Variable is " & stSubName'
End Function
And here is my SQL from inside of Access 2007:
SELECT DISTINCTROW Subs.Subcontractor, Counties.County, Projects.ContractID,
Sum(Project_Items.USTons) AS SumOfUSTons, Projects.PlanQuantity,
Max(Project_Items.EstDate) AS MaxOfEstDate, Project_Items.Sub
FROM Counties INNER JOIN (Subs INNER JOIN (Projects INNER JOIN Project_Items ON
Projects.ContractID = Project_Items.ProjectID) ON Subs.VendID = Project_Items.Sub) ON
Counties.ID = Project_Items.County
WHERE (((Projects.Completed)<>True) AND ((Subs.Subcontractor)=GetSubName()))
GROUP BY Subs.Subcontractor, Counties.County, Projects.ContractID,
Projects.PlanQuantity, Project_Items.Sub;
The reason the functions are not recognized is that you haven't fully specified the name. A public function in a form module needs to be specified with the form name:
Forms!MyForm.GetSubName()
But this is the wrong approach, and your code is way too convoluted. You can access the value of the combo box in your query directly:
Forms!MyForm!SubcontractorCombo
Now, the fact that you're using .SelText suggests to me either that you're doing something very very tricky, or you have your combo box set up wrong. Combo boxes can have a found field and a display value, such that a list of employees might display the employee LastName/FirstName while the combo box actually has as its bound field the EmployeeID.
If your combo box has a hidden bound field, but you want the displayed value, you don't need to use .SelText -- just use the appropriate .Column() of the combo box:
Forms!MyForm!SubcontractorCombo.Column(1)
(the column count is zero-based, so the hidden column would be column 0, assuming it's the first column that is hidden)
Also, there's an issue that if the user selects PART of the text in the combo box, you'd have an incomplete match, so you really don't want to use .SelText at all.
So, the WHERE clause of your SQL would end up being this (assuming I've diagnosed everything correctly):
WHERE Projects.Completed<>True
AND Subs.Subcontractor=Forms!MyForm!SubcontractorCombo.Column(1)
...and you can lose all of the marked code:
Option Compare Database
Option Explicit
<strike>Private stSubName As String</strike>
Private Sub Command2_Click()
On Error GoTo Err_Command2_Click
Dim stDocName As String
Dim stSubName As String
SubcontractorCombo.SetFocus
<strike>stSubName = SubcontractorCombo.SelText</strike>
'Confirm that stSubName variable is holding correct value'
<strike>MsgBox "Name of Subcontractor Selected is " & stSubName</strike>
<strike>SetSubName stSubName</strike>
<strike>GetSubName</strike>
DoCmd.Close
stDocName = "Summary Asphalt Production for Subcontractor"
DoCmd.OpenQuery stDocName
Exit_Command2_Click:
Exit Sub
Err_Command2_Click:
MsgBox Err.Description
Resume Exit_Command2_Click
End Sub
<strike>Public Sub SetSubName(Value As String)
'Set the module variable to be the value passed in from externally'
stSubName = Value
End Sub</strike>
<strike>Public Function GetSubName() As String
'Returns the value of the module variable'
GetSubName = stSubName
'MsgBox "GetSubName Variable is " & stSubName'
End Function</strike>
Would an alternative approach work?
Create a table (SubNameTable) with one field: SubName.
Add one record to it.
Then change your Sub to this:
Public Sub SetSubName(Value As String)
CurrentDb.Execute ("Update SubNameTable Set SubName = '" & Value & "'")
End Sub
Now you can Remove the function and modular variable.
Then, alter your SQL as such:
SELECT
*BlahBlahBlahFields*
FROM
*BlahBlahBlahTables*
INNER JOIN Subs
INNER JOIN SubNameTable ON Subs.SubContractor = SubNameTable.SubName
WHERE (((Projects.Completed)<>True)
GROUP BY
Subs.Subcontractor,
Counties.County,
Projects.ContractID,
Projects.PlanQuantity,
Project_Items.Sub
Not that this is the greatest solution, but should solve some future problems of trying to reference a function in a form. You could use a parameter on your query and set its value to the combo box.
You should put the public functions in a Module. I called this one Module2
Option Compare Database
Option Explicit
Private stSubName As String
Public Sub SetSubName(Value As String)
'Set the module variable to be the value passed in from externally'
stSubName = Value
End Sub
Public Function GetSubName() As String
'Returns the value of the module variable'
GetSubName = stSubName
'MsgBox "GetSubName Variable is " & stSubName'
End Function
Your form will reference the functions in the module:
Option Compare Database
Option Explicit
Private stSubName As String
Private Sub Command2_Click()
On Error GoTo Err_Command2_Click
Dim stDocName As String
Dim stSubName As String
SubcontractorCombo.SetFocus
stSubName = SubcontractorCombo.SelText
'Confirm that stSubName variable is holding correct value'
MsgBox "Name of Subcontractor Selected is " & stSubName
Module2.SetSubName stSubName
Module2.GetSubName
DoCmd.Close
stDocName = "Summary Asphalt Production for Subcontractor"
DoCmd.OpenQuery stDocName
Exit_Command2_Click:
Exit Sub
Err_Command2_Click:
MsgBox Err.Description
Resume Exit_Command2_Click
End Sub
The query will be able to find the public function in the module.

MS Access: Order of Events in event ApplyFilter (ADP Project)

I'm having problems with the execution of ServerFilterByForm in Access 2003
When I apply the entered filter it returns the requested data but after it appear on screen (Form) it disappears. Don't know why this is happening
Does anyone had the same problem? How can it be solved?
Here is part of the code"
Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)
Dim stSql As String
If Len(ServerFilter) > 0 Then
stSql = "SELECT * FROM v_InitialReviewQuery " & _
" WHERE " + ServerFilter & _
" ORDER BY acctnumber"
Else
stSql = "SELECT top 1 * FROM v_InitialReviewQuery ORDER BY acctnumber"
End If
Me.RecordSource = stSql
End Sub
Try changeing this line
" WHERE " + ServerFilter & _
To
" WHERE " & ServerFilter & _
Also what is the value of ServerFilter?
I have a similar .adp.
The method I use to set the queue is a view on a form (I use it as a subform that has various process queues) that provides the critera for the serverfilter. This would replace your "select top 1 *" and me.recordsource. The form is imbedded as a sub form on a main form that I provide information about various queues. Number in line, next to be worked, next SLA expiration... I use this to open the initial form:
Dim stDocName As String
Dim stLinkCriteria As String
Dim Next_TD_ID As String
Forms![Launch_Control]![queue_subfrom].Form.Refresh
Next_ID = Forms![Launch_Control]![queue_subfrom].Form.[nxt_id]
stLinkCriteria = "nxt_ID = " & Next_ID
stDocName = "Work_form"
DoCmd.OpenForm stDocName, , , stLinkCriteria
Then on the work_form I use 2 buttons
One for the next work_item in the que:
private sub next_button_click()
dim nxt_id as string
nxt_id = Forms![Launch_Control]![queue_subfrom].Form![nxt_id]
Me.ServerFilter = "identifier_in_view = " & Nxt_id
Me.Refresh
end sub
The other to call the filterby from command.
Private Sub button_click(button As String)
Forms![your_form].Reviewer.SetFocus
Me.ServerFilter = ""
Me.Refresh
Me.ServerFilterByForm = True
Me.Refresh
DoCmd.RunCommand acCmdServerFilterByForm
end Sub
FYI my subform refrence may not be exacly correct.
Hope this helps.

Compile time: Syntax error

I am able to add controls to a form when it is loaded. I need these controls to be to be catagorized so the user only can see a few at a time. My first thought was to attached the controls to particular tabs. Not sure why the syntax is off in the following code. Thanks for the help!
Private Sub Enter_Records_Click()
Dim stDocName As String
Dim tabPage As String
Dim tabNum As Integer
Dim i As Integer
Dim passedTabName As String
stDocName = "CLForm"
tabPage = "tabControl.tabPage"
stTabName = stDocName & tabPage
tabNum = 8 'the number of tabs on the "CLForm"
DoCmd.OpenForm stDocName, acDesign
For i = 0 To tabNum - 1
passedTabName = stTabName & i
CreateKeywords (stDocName, passedTabName)
Next i
DoCmd.Close acForm, stDocName, acSaveYes
DoCmd.OpenForm stDocName, acNormal
End Sub
Public Sub CreateKeywords(frmName As String, tabName As String)
Another idea that might be better, simply having buttons that show one category of controls at a time. Would this be easier?
You need to use the Call keyword when calling a method with more than one parameter and using parentheses.
For example, these would work:
Call CreateKeywords(stDocName, passedTabName)
CreateKeywords stDocName, passedTabName
//Example of using parentheses with one parameter
Msgbox (stDocName)
Welcome to the wonderful world of VBA. ;)
It is best be careful with calling arguments and parentheses:
Public Sub CallingSub()
CallingArg = "ABCDEF"
CalledFunc CallingArg
Debug.Print CallingArg ''Result: 987654
CallingArg = "ABCDEF"
CalledFunc (CallingArg) ''Result: ABCDEF
Debug.Print CallingArg
CallingArg = "ABCDEF"
Call CalledFunc(CallingArg)
Debug.Print CallingArg ''Result: 987654
End Sub
Public Function CalledFunc(CalledFuncArg)
CalledFuncArg = "987654"
CalledFunc = "Return"
End Function