VBA Basic Function returning null - ms-access

I have a very basic function that is to return symbols such as "=", ">","<",">=", and "<=" and it is only returning a null value. any Ideas?
Function Lookup_Symbol(search_Name As String) As String
Lookup_Symobl = DLookup("[Symbol]", "[Search_Names]", "[Search_Name]= '" & search_Name & "'")
End Function
when I do a Debug.print DLookup("[Symbol]", "[Search_Names]", "[Search_Name]= '" & search_Name & "'") it will return =

Because you have misspelled Lookup_Symbol in your function. It should be:
Function Lookup_Symbol(search_Name As String) As String
Lookup_Symbol = DLookup("[Symbol]", "[Search_Names]", "[Search_Name]= '" & search_Name & "'")
End Function
You would have been able to spot this much easier if you had Option Explicit at the top of the module; it would then have told you that the variable Lookup_Symobl is not defined.

Related

VBA returning a value and error information together

I am writing some VBA in MS Access, although the principle of my question would apply just as well to Excel or Word VBA. I have written a function GetStringParameterFromTable which returns a string value. It is possible that the function may result in a VBA-generated error, despite my best efforts to write it so that it does not. If an error happens, I don't want the code to crash, so I must use error handling. However, I don't want the code to display an error message and stop within the function if there is an error. I want the function to finish executing and return control to the calling procedure, and then I want the calling procedure to display the error message and tidy up, e.g. close open files. My question is: how does the calling procedure know that there has been an error in the function it called, and how does it get the error message?
I have thought of three ways of implementing this:
(1) Make GetStringParameterFromTable into a Sub, and pass it ParameterValue, ErrorFlag and ErrorMessage by reference.
(2) Keep GetStringParameterFromTable as a Function, define ErrorFlag and ErrorMessage as global variables and have the function alter ErrorFlag and ErrorMessage.
(3) Keep GetStringParameterFromTable as a Function and define a type with three components – ParameterValue, ErrorFlag and ErrorMessage – and make GetStringParameterFromTable return a value of the type I have defined.
I think that my requirement must be quite common, but I can’t find any examples of how it’s implemented. Does anyone have any views on which of my suggestions is the best way, or whether there is a better way that I haven’t thought of?
I have been contemplating the same thing since C#.net has implemented Tuples. I have implemented Tuples using VBA's type to create my tuples. What I have done is the following:
Public Type myTuple
Value as String 'Or whatever type your value needs to be
ErrCode as Long
ErrDesc as String
End Type
Public Function DoWork (ByRef mObject as MyClass) as myTuple
Dim retVal as myTuple
'Do whatever work
If Err.Number <> 0 then
retVal.Value = Nothing
retVal.ErrNumber = Err.Number
retVal.ErrDesc = Err.Description
Else
Set retVal.Value = Whatever Makes Sense
retVal.ErrNumber = 0
retVal.ErrDesc = VbNullString
End If
DoWork = retVal
End Function
I would like to be more specific, but you didn't provide a code example.
I am doing it like this and log the errors in a table:
' Lookups Replacements
'---------------------
Function DLook(Expression As String, Domain As String, Optional Criteria) As Variant
On Error GoTo Err_Handler
Dim strSQL As String
strSQL = "SELECT " & Expression & " FROM " & Domain 'DLookup
'DCount: strSQL = "SELECT COUNT(" & Expression & ") FROM " & Domain
'DMax: strSQL = "SELECT MAX(" & Expression & ") FROM " & Domain
'DMin: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DFirst: strSQL = "SELECT FIRST(" & Expression & ") FROM " & Domain
'DLast: strSQL = "SELECT LAST(" & Expression & ") FROM " & Domain
'DSum: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DAvg: strSQL = "SELECT AVG(" & Expression & ") FROM " & Domain
If Not IsMissing(Criteria) Then strSQL = strSQL & " WHERE " & Criteria
DLook = DBEngine(0)(0).OpenRecordset(strSQL, dbOpenForwardOnly)(0)
Exit Function
Err_Handler:
'Can be made as Error Sub as well
Dim ErrNumber as Integer
Dim ErrDescription as String
ErrNumber = Err.Number
ErrDescription = Err.Description
Err.Clear
On Error Resume Next
Dim strSQL as String
strSQL = "INSERT INTO tblErrorLog (ErrorNumber, ErrorDescription) VALUES (" & ErrNumber & ", '" & ErrDescription & "')"
Currentdb.Excecute strSQL, dbFailOnError
End Function
Called with:
If DLook("Column2", "Table1", "Column1 = " & ID) = 0 Then
'Do stuff
End If
If DLook("Column2", "Table1") = 0 Then
'Do other stuff
End If

Access Form - Current Records Count

I created a public function, so that I could call it on Access forms, and display the result in a textbox control. This is the public function:
Public Function CurrRecs(xRecName As String, frmName As Form, tblCount As String)
If Forms(frmName).NewRecord Then
frmName.txtCurrRec = "New " & xRecName & " Record"
Else
frmName.txtCurrRec = CStr(frmName.CurrentRecord) & " of " & _
DCount("ID", tblCount) & " " & xRecName & "s"
End If
End Function
This is what I have on the Form_Current()
CurrRecs("RecordType", "frmCurrentForm", "tblGetCountFromHere")
I get a compile error: Expected:=
Anyone know what I'm doing wrong?
The error is because you're declaring frmName as a form, but using it as a string in one place, and a form in another
Also, if you want the table count, use Form.RecordSet.RecordCount, not an elaborate DCount
Rewritten:
Public Function CurrRecs(xRecName As String, frmName As String)
Dim frm As Form
Set frm = Forms(frmName)
If frm NewRecord Then
frm.txtCurrRec = "New " & xRecName & " Record"
Else
frm.txtCurrRec = CStr(frm.CurrentRecord) & " of " & _
frm.RecordSet.RecordCount & " " & xRecName & "s"
End If
End Function

Issue with Data passing from one form to another form in MS Access VBA

Can anyone solve my issue
Form: SB_1 (this is a Customer Invoice creation form)
Form: Add_NewRelations (this is a Customer details adding form)
I have used a VBA code in Form: SB_1 on a cmd (Button) for Data passing from one form to another form of Add_NewRelations for New Customer details are needed to update.
So that VBA working is good as per Code Tag. But some of exist customer details are no need to update into Form: Add_NewRelations. So in this case i have added IF Statement with DCount in the VBA code.
When i added If statement with DCount then whole VBA is didn't working... i think DCount is wrong... how can i correction it??
Can anyone please replay how to solve this problem??
Private Sub Button_Click()
On Error GoTo ErrorHandler
'Me.Refresh
Dim strCriteria As String
strCriteria = "CIDCustomer = '" & Trim(Trim(Me!RID) & " " & Trim(Me!RName)) & "'"
'If DCount("*", "CIDCustomer", "RelationsQry") > 0 Then
'Cancel = True
'Else
If DCount("*", "RelationsQry", strCriteria) > 0 Then
Cancel = True
Else
'If Not IsNull([Customer]) Then
'Me.Visible = False
DoCmd.OpenForm "Add_NewRelations", acNormal, , , , acWindowNormal
Forms![Add_NewRelations].Form.RID = Me.CID2
Forms![Add_NewRelations].Form.RName = Me.Customer
Forms![Add_NewRelations].Form.RType.Value = "Customer"
Forms![Add_NewRelations].Form.Address = Me.Address
Forms![Add_NewRelations].Form.TINNumber = Me.TINNumber
Forms![Add_NewRelations].Form.TownVLG = Me.TownVLG
Forms![Add_NewRelations].Form.RName.SetFocus
'Forms![Add_NewRelations].Visible = False
'DoCmd.Close
End If
ErrorHandler:
End Sub
To pass the quotes into the SQL you need to escape them, and you need additional single quotes as well for the elements of the criteria.
Instead of:
strCriteria = "CIDCustomer = '" & Trim(Trim(Me!RID) & " " & Trim(Me!RName)) & "'"
try
strCriteria = "" "CIDCustomer = '" & Trim(Trim(Me!RID) & "' & " " & '" Trim(Me!RName)) & "'" ""

Using User Defined Function output from VBA as an input in access query

I have created a function that provide the value based on user selection.I want to use the output of the fuinction in another query.
My function is :-
Public Function provisionvariable() As String
For Each sItem In Forms![Access Form].Provision.ItemsSelected
v_provision = "" & Forms![Access Form].Provision.Column(0, sItem) & ""
Provision = Provision & "" + v_provision + ","
'MsgBox Provision
Next
Provision = Left(Provision, Len(Provision) - 1)
provisionvariable = Provision
MsgBox provisionvariable
End Function
The output of the function is BBNI,FP
I want to use the output as where condition in access query
My query is
***SELECT DISTINCT quarter, provision, [currencycode]+'-not found in Master' AS Comment
FROM t_00_unearned_unincepted_alloc_basis AS inp
WHERE **provision in (provisionvariable()) AND**
NOT EXISTS
(SELECT 1
FROM t_01_le_currency_master key1
WHERE inp.[group_stat]=key1.[group_stat] AND
inp.le=key1.le AND
inp.[currencycode]=key1.[original_currency]);***
Now the problem is output of function is BBNI,FP but access takes it as single string i.e. 'BBNI,FP' in the query.
Is it possible to have it as two string ('bbni','FP') rather than 'BBNI,FP'
Any Suggestions Much Appreciated
Thanks
Try:
Provision = Provision & "'" & v_provision & "',"
And to ensure you aren't repeatedly appending to a module-level variable, you should also do a local
Dim Provision As String
Based on the following post, "a function cannot be used for IN () clauses" How to call VBA-function from inside sql-query?
So you need to build the SQL (which would include the 'In' list) then execute it. Since I have no idea if multi-user environment, or how you will use the query output, I would build the SQL, save as a QueryDef object, then do whatever you want.
The following is what the code to build the SQL could look like:
Dim strSQL As String
strSQL = "SELECT DISTINCT quarter, provision, [currencycode]+'-not found in Master' AS Comment " & _
"FROM t_00_unearned_unincepted_alloc_basis AS inp " & _
"WHERE provision In (" & ProvisionVariable() & ") AND " & _
. . . .
Debug.Print strSQL
The following is my version of your Function (note the single-quote delimiters are added):
Public Function ProvisionVariable() As String
Dim sItem As Variant
Dim v_provision As String
Dim provision As String
provision = ""
For Each sItem In Forms![Access Form].Provision.ItemsSelected
v_provision = "'" & Forms![Access Form].Provision.Column(0, sItem) & "'"
provision = provision & "" + v_provision + ","
Next sItem
provision = left(provision, Len(provision) - 1)
ProvisionVariable = provision
Debug.Print ProvisionVariable
End Function

DSum function in vba

I want to display sum of a column in a textbox when I hit a button. But it is giving me a compile error: "Wrong number of arguements or invalid property assignment"
The below code is implemented in vba.
Here is the code that I used:
Text19 = Nz(DSum("Total_Units", "6_Provincial_SUB", , "[BudgetYear] =" & [Combo5] & " And [Program_Name] ='" & Replace([Combo7], "'", "''") & "'"), 0)
DSum has three parameters. You have four. Drop the extra comma
Text19 = Nz(
DSum(
"Total_Units",
"6_Provincial_SUB", <==== Here I dropped a comma (,)
"[BudgetYear] =" & [Combo5] & " And [Program_Name] ='" &
Replace([Combo7], "'", "''") & "'"
),
0
)
When things like this happen, I try to find the problem by indenting the expression like above in order to find matching braces etc. Without line continuation character "_" this will not work of cause, but it gives you an idea of the structure of the expression.
I have these functions in my library. They help me in the creation of SQL strings
Public Function SqlStr(ByVal s As String) As String
'Input: s="" Returns: NULL
'Input: s="abc" Returns: 'abc'
'Input: s="x'y" Returns: 'x''y'
If s = "" Then
SqlStr = "NULL"
Else
SqlStr = "'" & Replace(s, "'", "''") & "'"
End If
End Function
Function Build(ByVal s As String, ParamArray args()) As String
'Build("FirstName = {0}, LastName = {1}","John","Doe") -->
'"FirstName = John, LastName = Doe".
'"\n" is expanded with vbCrLf.
Dim i As Long
s = Replace(s, "\n", vbCrLf)
For i = 0 To UBound(args)
s = Replace(s, "{" & i & "}", Nz(args(i)))
Next i
Build = s
End Function
By using them, your SQL would be constructed like this
sql = Build("[BudgetYear] = {0} AND [Program_Name] = {1}", _
Combo5, SqlStr(Combo7))
You have a comma too many after the domain parameter:
"6_Provincial_SUB", ,
That would make the space the criteria parameter, and the actual criteria an unknown fourth parameter.