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
Related
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
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
I am attempting to connect to a MongoDB database:
Dim server As MongoServer = MongoServer.Create("mongodb://localhost")
Dim db As MongoDatabase = server("mydb")
Dim coll As MongoCollection = db("coll")
Dim query = New QueryDocument("name","sid")
Dim item As BsonDocument = coll.FindOneAs(query)
The last line throws an error, and reads:
Public Overridable function FindOneAs(documentType As System.Type)As Object': Value of type MongoDB.driver.queryDocument cannot be converted to System.Type
Now I know that the object passed here is most probably of Type, but then I am not able to proceed. What should I pass instead of QueryDocument to execute my query?
You should be using the static methods of the Query class, like EQ which means equals. The other operators for MongoDb are also located on that class. You can find the details here.
Dim server As MongoServer = MongoServer.Create("mongodb://localhost")
Dim db As MongoDatabase = server("mydb")
Dim coll As MongoCollection = db("coll")
Dim query = Query.EQ("name","sid")
Dim item As BsonDocument = coll.FindOneAs(query)
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 have a query saved in the queries section. I am running the query from VBA. Is it possible to save the results of this query to a string?
An ADO Recordset has a GetString method which might be useful to you.
I have a query named qryListTables which looks like this:
SELECT m.Name AS tbl_name
FROM MSysObjects AS m
WHERE
(((m.Name) Not Like "msys%"
And (m.Name) Not Like "~%")
AND ((m.Type)=1))
ORDER BY m.Name;
Notice that query uses % instead of * as the wildcard character. The reason for that choice is that ADO requires ANSI wild card characters (% and _ instead of * and ?).
I can use the following function to spit out a string containing the quoted names of regular tables in my database, separated by semicolons, by calling it like this:
? DemoGetString("qryListTables", True)
Public Function DemoGetString(ByVal pQueryName As String, _
Optional ByVal AddQuotes As Boolean = False) As Variant
'* early binding requires a reference to Microsoft ActiveX
'* Data Objects Library
'Dim rs As ADODB.Recordset
'Set rs = New ADODB.Recordset
'* use late binding; no referenced needed
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
Dim varOut As Variant
rs.Open pQueryName, CurrentProject.Connection
If AddQuotes Then
varOut = """" & rs.GetString(2, , , """;""") '2 = adClipString
' strip off last quote
If Len(varOut & vbNullString) > 0 Then
varOut = Left(varOut, Len(varOut) - 1)
End If
Else
varOut = rs.GetString(2, , , ";") '2 = adClipString
End If
rs.Close
Set rs = Nothing
DemoGetString = varOut
End Function
Ok.. taking a complete shot in the dark here...
The query you are running is literally a query... think of it as its OWN table... it can be referenced as you would any other table, and can be queried against.
If you are trying to return a single string item based on a single criteria your best bet is a Dlookup:
Lookup = Nz(DLookup(string Field, string Table, string Criteria), "")
If your looking for a group of records:
dim tsSQL as string
stSQL = "SELECT * FROM table WHERE field=criteria"
dim toRecordset as new ADODB.Recordset
toRecordset.open stSQL, CurrentProject.AccessConnection, int Keyset, int Lock
Then you can directly access the fields by:
If toRecordset.RecordCount > 0 then
String = toRecordset!FieldName
End If
W/o more information... that about it...
Also it works in the other direction as well..
You can do:
toRecordset.AddNew
toRecordset!Field = Value
toRecordset.Update
I hope somewhere in there is an answer for you.
To get the entire query you could change up the select statement from example one to "SELECT * FROM query name" and that should pull the whole thing in.