I have an MS Access database (I'm not after reasons to not use Access).
I am trying to run a VBA sub to cycle through some queries based on a parameter, which is a query result.
There's a query which sums the value in the table for a column.
I need to return this with a function in VBA using an IF ELSE statement to proceed.
Public dbs As DAO.Database
Sub Main()
Dim SumCheck As Double
Set dbs = CurrentDb
GoTo LoopCheck
LoopCheck:
SumCheck = SOSum(dbs)
If SumCheck = 0 Then
GoTo EndPart
Else
GoTo STPTGet
End If
The code doesn't proceed past here, instead when I step into the code it stops here at this function and gives the error "Expected Function or Value"
Public Function SOSum(db As DAO.Database) As Double
Dim sumg As Double
Set db = dbs
Set sumg = db.Execute("LoopCheck")
Set db = Nothing
Set SOSum = sum
End Function
The loop check query is simple
SELECT SUM(Qty)
FROM SO;
The query works in Access, it should just check if it's 0 or not.
This is my first post, so excuse any incorrect formatting or obviously missing information. Any help is greatly appreciated.
Thank you
There are a few issues with your code.
First, it looks like you have dbs as a public Database object. Because of this, you don't need to pass it around to your function. You can just use it once it has been set.
Next, the db.execute method will only run action queries (like INSERT, UPDATE, DELETE...) and it doesn't return anything. You'll need to use a recordset to get at the results of your query.
Lastly, your function returns a Double, so you shouldn't be using the Set keyword to return the value.
Put all together we have this:
A Database object Global Declaration:
Public dbs as DAO.Database
A MAIN Sub (only partial was given in the question):
Sub Main()
Dim SumCheck As Double
Set dbs = CurrentDb
'...
SumCheck = SOSum
'...
And your SOSum Function:
Public Function SOSum() As Double
Dim sum As Double
Dim rs As DAO.Recordset
Set rs= dbs.OpenRecordset("LoopCheck")
sum = rs(0).Value
Set rs = nothing
SOSum = sum
End Function
Related
Objective: I'm building VBA code to filter through an address table SunstarAccountsInWebir_SarahTest. I want to loop through first and see if the address is "valid".
If it is not valid – export to different table.
If it is valid – it enters another nested if/then within "valid" address rows:
If their ID, external_nmad_id matches the ID of the second table 1042s_FinalOutput_7, I want to update one of the columns in the second table box13c_Address.
If it doesn't match an ID of the second table – it will be exported to a different table.
My problem is when I run my code it is returning
Run-Time error 3078: cannot find table or query
(it's breaking at the line where I compare the value of the cell (as string) against the DCount of table 2). If I remove the quotes around it I get a different error:
Type mismatch against the DCount
I feel like I'm missing something simple but can't tell what. How can I get my code to match a string value called in !external_nmad_id against the rest of the table called in my string? DCount("[ID]", StrSQL1)
Public Sub EditFinalOutput2()
'set variables
Dim i As Long
Dim qs As DAO.Recordset
Dim ss As DAO.Recordset
Dim StrSQL1 As DAO.Recordset
Dim IRSfileFormatKey As String
Dim external_nmad_id As String
Dim nmad_address_1 As String
Dim nmad_address_2 As String
Dim nmad_address_3 As String
Dim mytestwrite As String
'open reference set
Set db = CurrentDb
Set qs = db.OpenRecordset("SunstarAccountsInWebir_SarahTest")
'Set ss = db.OpenRecordset("1042s_FinalOutput_7")
'Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID
'FROM 1042s_FinalOutput_7;")
With qs.Fields
intCount = qs.RecordCount - 1
For i = 0 To intCount
If (IsNull(!nmad_address_1) Or (!nmad_address_1 = !nmad_city) Or (!nmad_address_1 = !Webir_Country) And IsNull(!nmad_address_2) Or (!nmad_address_2 = !nmad_city) Or (!nmad_address_2 = !Webir_Country) And IsNull(!nmad_address_3) Or (!nmad_address_3 = !nmad_city) Or (!nmad_address_3 = !Webir_Country)) Then
DoCmd.RunSQL "INSERT INTO Addresses_ToBeReviewed SELECT SunstarAccountsInWebir_SarahTest.* FROM SunstarAccountsInWebir_SarahTest WHERE (((SunstarAccountsInWebir_SarahTest.external_nmad_id)='" & qs!external_nmad_id & "'));"
Else:
Set ss = db.OpenRecordset("1042s_FinalOutput_7")
Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;")
If !external_nmad_id = DCount("[ID]", StrSQL1) Then
ss.Edit
ss.Fields("box13c_Address") = qs.Fields("nmad_address_1") & qs.Fields("nmad_address_2") & qs.Fields("nmad_address_3")
ss.Update
Else: DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO Addresses_NotUsed SELECT SunstarAccountsInWebir_SarahTest.* FROM SunstarAccountsInWebir_SarahTest WHERE (((SunstarAccountsInWebir_SarahTest.external_nmad_id)='" & qs!external_nmad_id & "'));"
DoCmd.SetWarnings True
End If
End If
qs.MoveNext
Next i
End With
'close reference set
qs.Close
Set qs = Nothing
ss.Close
Set ss = Nothing
End Sub
The issue is that the DCount function cannot operate directly against a Recordset.
You are declaring StrSQL1 as a RecordSet object and setting it to a RecordSet based on your Select statement.
Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;")
You are then trying to pass this RecordSet to the DCount function which cannot accept a RecordSet object as the Domain parameter. As you can see in MSDN the DCount function requires a String parameter in the second position to define the "query" that you wish to "Count". Hence the 3078 error. When you remove the quotes around [ID] in your DCount line, you get Type Mismatch as a compile error because [ID] is not a String or String variable.
After you resolve that, you might want to reconsider your If statement. You haven't provided a sample of what kind of value !external_nmad_id will contain, other than the fact that it is a String value. The DCount function is going to return the number of rows found in the Domain (query) that you told it to count, so it appears you will be comparing a string (which may possibly contain alpha characters) to a number. Access will implicitly convert the DCount numeric result to a String for the sake of the comparison, but if your !external_nmad_id String is truly 10 characters or contains alpha characters, they will never match.
You cannot use a VBA recordset inside a domain aggregate like DCount as a string literal is required for table/query name argument. Simply save your query and then reference it by name in DCount.
SQL (save as query)
SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;
VBA
If !external_nmad_id = DCount("[ID]", "mySavedQuery") Then
...
End If
Function PrintTableDefs()
Dim aDB As DAO.Database
Dim aTD As DAO.TableDef
Dim aTableName As String
Dim aForeignTableName As String
Dim aString As String
Dim count As Integer
Set count = 0
Set aDB = CurrentDb()
For Each aTD In aDB.TableDefs
Debug.Print aTD.Name
Debug.Print aTD.Connect
Debug.Print ""
count = count + 1
Next
Debug.Print "There are " & count & "table defs."
End Function
When calling this function I get "Compile Error: Expected: =". I have noticed through other questions it is related to parentheses however being mildly unfamiliar with VBA I'm unsure where my syntax is off.
Remove the set from set count = 0
set is only for assigning object references and an Integer is not an object instance.
Alex pointed out the only issue in your function that could throw a compile error: you don't need a set to initialize your count variable, because it is not an object. The rest is correct and should not throw an error, so it is elsewhere.
However your code shows that you don't really understand what is the difference between a sub and a function and it might be helpful to explain it.
A function returns a value, a sub doesn't. That's what's make them different.
You are not returning any value so you should use a sub.
Although your code works fine, because functions that doesn't return a value are accepted by the VBA compiler, it is semantically incorrect and a bad programming habit.
You can make a proper function out of it by returning the number of tables you found (your count variable)
Sub test()
Debug.Print "There are " & PrintTableDefs() & " table defs."
End Sub
Function PrintTableDefs() As Integer
Dim aDB As DAO.Database
Dim aTD As DAO.TableDef
Dim aTableName As String
Dim aForeignTableName As String
Dim aString As String
Dim count As Integer
count = 0
Set aDB = CurrentDb
For Each aTD In aDB.TableDefs
Debug.Print aTD.Name
Debug.Print aTD.Connect
Debug.Print ""
count = count + 1
Next
PrintTableDefs = count
End Function
And if you don't need anything to be returned, make a sub:
Sub PrintTableDefs()
Dim aDB As DAO.Database
Dim aTD As DAO.TableDef
Dim aTableName As String
Dim aForeignTableName As String
Dim aString As String
Dim count As Integer
count = 0
Set aDB = CurrentDb
For Each aTD In aDB.TableDefs
Debug.Print aTD.Name
Debug.Print aTD.Connect
Debug.Print ""
count = count + 1
Next
Debug.Print "There are " & count & " table defs."
End Sub
Additionally, you don't need () when you assign the CurrentDb object :
Set aDB = CurrentDb
My experience is that when calling a function or subroutine in VBA, enclosing your parameters (or lack thereof) in parentheses will cause this error.
There are two ways I know of to handle this:
Just don't use parentheses and always call the sub or function without them. This is fine if you are going from "PrintTableDefs()" to "PrintTableDefs" but can be problematic if the call is nested in a control structure or as another parameter.
Keep your parentheses, because you like parentheses and they remind you of C based language syntax, which helps you forget you are using the sadness of VBA. In that case, always assign the value of a function to a variable "result = PrintTableDefs()" and always use the Call keyword when invoking subroutines.
As an aside: your function returns no value. You should probably replace it with a subroutine, which is done by just replacing the word "Function" with the word "Sub".
In Access 2007 database, I have a custom function called "IsIn" in Module1 that looks like this:
#TimWilliams: you have nailed the proble, I think. I think, then, I'll need to recode it in .Net which is fine, but then I'm not sure how to use the function in .Net and in SQL like that - do you have an example? Here's the whole function (I had shortened it for brevity):
Public Function IsIn(Arr1 As Variant, Arr2 As Variant) As Boolean
Dim comp1() As String
Dim comp2() As String
comp1() = Split(Arr1, " ")
comp2() = Split(Arr2, " ")
Dim x, y As Long
For x = LBound(comp1) To UBound(comp1)
For y = LBound(comp2) To UBound(comp2)
If comp1(x) = comp2(y) Then
IsIn = True
End If
Next y
Next x
End Function
I use it in a SQL query as such:
SELECT B.*
FROM TableA AS A, TableB AS B
WHERE IsIn(A.Field1,B.Field1)=True
This works fine as a query in Access.
But in my .aspx page, when I execute the query, it fails. I know the function is causing the problem, because the query works if I comment out just that line (the WHERE) clause. When the SQL executes, it executes successfully, but returns no rows.
My SQL code is as follows, and works everywhere else in my website just fine - and works if the function line in the SQL is commented out:
rstResult = ExecQuery(SQL), where SQL is the SQL from above
Public Function ExecQuery(ByVal SQL_Query As String)
Try
OpenDB
Dim OleDbCmd As New OleDbCommand(SQL_Query,conn)
Dim OleDbAdapter As New OleDbDataAdapter(OleDbCmd)
Dim DT As New DataTable
OleDbAdapter.Fill(DT)
CloseDB
OleDbAdapter.Dispose()
OleDbCmd.Dispose()
Return DT
Catch ex as Exception
LogSQLError(ex,"methodName")
End Try
End Function
Any help is appreciated - thanks
I'm new to VBA and i need help.
I want to create vba function which takes table name as input, and distinct specific field from that table. I created function, and it works when i run it in vba immediate window (when i use debug.print command to display results). But when i call this function in sql, instead whole field values, it returns just last one. I'm not good at vba syntax so i need help to understand. Does function can return more than one value? If can, how, and if not what else to use? Here's my code:
Public Function TableInfo(tabela As String)
Dim db As Database
Dim rec As Recordset
Dim polje1 As Field, polje2 As Field
Dim sifMat As Field, pogon As Field, tipVred As Field
Set db = CurrentDb()
Set rec = db.OpenRecordset(tabela)
Set sifMat = rec.Fields("Field1")
Set pogon = rec.Fields("Field2")
Set tipVred = rec.Fields("Field3")
For Each polje1 In rec.Fields
For Each polje2 In rec.Fields
TableInfo = pogon.Value
rec.MoveNext
Next
Next
End Function
Any help is appreciated.
The problem is with this line probably:
TableInfo = pogon.Value
It runs inside the loop and returns the last value of the loop.
Instead of returning one value TableInfo, you may try to return something similar to a Collection or an Array.
Inside the loop, append values in the Collection and after the loop, return the Collection back from the function.
Edit:
I have re-written the code shared by you:
Public Function TableInfo(tabela As String) as String()
Dim db As Database
Dim rec As Recordset
Dim polje1 As Field, polje2 As Field
Dim sifMat As Field, pogon As Field, tipVred As Field
Dim returnValue() As String
Dim i as Integer
Set db = CurrentDb()
Set rec = db.OpenRecordset(tabela)
Set sifMat = rec.Fields("Field1")
Set pogon = rec.Fields("Field2")
Set tipVred = rec.Fields("Field3")
' I am not going to modify this but I think we can do away with two For Each loops.
' Just iterate over rec like
' For Each r In rec -> please use proper naming conventions and best practices
' and access each field as r("Field1") and r("Field2")
For Each polje1 In rec.Fields
For Each polje2 In rec.Fields
returnValue(i) = pogon.Value
i = i + 1
rec.MoveNext
Next
Next
TableInfo = returnValue
End Function
Please note: I have not tested this code but I assume this should work for you. Also, I have assumed that you want to return String() array. Please change the data type if you want to return some other type.
When you call the array (as posted in theghostofc's answer), you will need to do something like this:
Dim TableInfo() As String
For i = LBound(TableInfo) To UBound(TableInfo)
YourValue = TableInfo(i)
... Process some code that uses YourValue
Next i
If you're not looping through your array, you're not going to get each individual value out of it.
I need to access the salary field of an employee table based on the entered username from ms access in vb6.. I read the username and password in a form and enter into another form that displays the salary corresponding to the username. I am using Adodc1 connection. I know SQL but dunno how to implement it in vb... I want to know exactly where to use the sql query?
Thanks
If you are using DAO, this should help. Add the following functions to a module, and pass in MyDB a reference to the OPENED database (of datatype DAO.Database, use the DAO.OpenDatabase() function to open a database):
Public Function GetQueryResults(ByRef MyDB as DAO.Database, SQLQuery As String) As DAO.Recordset
Dim Q As DAO.QueryDef, R As DAO.Recordset
Set Q = MyDB.CreateQueryDef("", SQLQuery)
Set R = Q.OpenRecordset
Set GetQueryResults = R
End Function
Public Function GetFirstValueFromQuery(MyDB As DAO.Database, SQLQuery As String) As String
If (MyDB Is Nothing) Then Exit Function
Dim RES As DAO.Recordset, T As String
Set RES = GetQueryResults(MyDB, SQLQuery)
With RES
T = .Fields(0).Value
GetFirstValueFromQueryGeneral = T
End With
RES.Close
End Function
now, call this function from every form (wherever u need to run a SQL query):
Dim A as String
A=GetFirstValueFromQuery(MyDatabase, "SELECT Employee.Salary FROM Employee WHERE Employee.UserName='"+uname+"'")
Msgbox "Salary="+A