VBA function to get windows user name [duplicate] - windows

I would like to know if there is a way to get system username and use it directly in an MS Access query. I have made a parameter work within a query from a combo box on a form and I have also acquired system name in Access VBA using ENVIRON ("USERNAME").
Kindly let me know if this is possible.

You need to create a VBA function that returns the username, and then use the function in the query.
Public Function GetUserName() As String
' GetUserName = Environ("USERNAME")
' Better method, see comment by HansUp
GetUserName = CreateObject("WScript.Network").UserName
End Function
and
SELECT foo FROM bar WHERE myUserName = GetUserName();

My solution kept all the work in VB.
I used a variable for the windows login username and then created a SQL string with that variable inserted. Lastly, I updated the query behind the form to use this new SQL string.
The CHR(34) puts quotes around the name as it is now a string inside the SQLSTR and needs to be within a set of quotes.
If you have a complex SQL statement, write it in the QBE using a string for the name and all the other variables, then switch to the SQL view and replace it using a VBA variable as shown below.
MyName = Environ("username")
sqlstr = "SELECT * From Projects WHERE ( ((Projects.LeadEngineer)=" & Chr(34) & MyName & Chr(34) & " AND ActiveYN = True ));"
Forms![Main Form].RecordSource = sqlstr

You can use SYSTEM_USER if the query is being executed in a SQL Server, that will retrieve the user name connected to the database (for that, make sure you are not using fixed user name in your connection string)

Yes - you can use the 'CurrentUser' function in your query. Here I've included it as a field and criteria.
SELECT Field1, Field2, [CurrentUser] AS UserName FROM Table1 WHERE Field1 = [CurrentUser];

Related

How to use a variable for the criteria in a query to restrict the query to the active form?

I have form named "frmBond-MuniDetailsAE". It has a combo box named "cboStep". The Row Source for cboSteps is an embedded query that retrieves records from a table named "tblBond-Steps", and it has as Criteria -
[Forms]![frmBond-MuniDetailsAE]![SYM]. This restricts the query to records in tblBond-Steps to only those that have a SYM field that matches that field in the form. This works fine. But I would like to be able to copy and reuse the form for other types of bonds, and I don't want to have to rewrite the embedded query in each copied form. So I wanted to use a variable in the query criteria that would reference the current form.
Following answers given in StackOverflow at How do I reference the current form in an expression in Microsoft Access?, I wrote a Public Function named "FormName()". Here is the function:
Public Function FormName() As String
Dim frmCurrentForm As Form
Set frmCurrentForm = Screen.ActiveForm
FormName = "[Form]![" & frmCurrentForm.Name & "]" & "![SYM]"
End Function
Then in the embedded query for the combo box, I entered "FormName()" as the criteria. Here is the SQL for that query:
SELECT [tblBond-Steps].SYM, [StepDate] & " # " & [Cpn] AS Steps, Format([tblBond-Steps].
[StepCpn],"0.0000%") AS Cpn, [tblBond-Steps].StepDate
FROM [tblBond-Steps]
WHERE ((([tblBond-Steps].SYM)=FormName()))
ORDER BY [tblBond-Steps].StepDate;
But when I open the form with the above query as the Row Source for cboSteps, I get VBA Run-time error '2475': "You entered an expression that requires a form to be the active window."
I can't figure out what I'm doing wrong. Can someone help me?
You must return the value, not the expression:
Public Function FormName() As String
Dim frmCurrentForm As Form
Set frmCurrentForm = Screen.ActiveForm
FormName = frmCurrentForm![SYM].Value
End Function

Dataset is empty

I have a problem, I'm working on a school project with Visual Basic and I can't manage to fill a dataset with a LIKE query.
I'm using Access in order to manage the database and the query is:
SELECT * FROM VistaProductos WHERE Nombre LIKE "*ta*"
In Access this query is working fine but when I use it on Visual Basic the OleDbDataAdapter fills my DataSet with 0 rows.
Here is the code:
Dim adaptador As New OleDbDataAdapter("SELECT * FROM VistaProductos WHERE " & campo & " LIKE ""*" & valor & "*""", conexion)
adaptador.Fill(dataset, tabla)
Return dataset
campo and valor are variables who have the same data as in the Access example, and I tried by writing them literally too.
The connection to the database is working fine as the other querys work perfectly.
ADO.NET uses the standard % character as wildcard in LIKE expressions.
But your first problem to solve is removing the string concatenations when you build sql queries. You cannot trust your user on this point. If you leave in that way you user can write anything and you risk to pass malicious commands to your database engine. You should always use parameters in these contexts
In your code is present also a field name as a variable part of the query.
This cannot be parameterized, so the only sensible solution is to present your user with a list of field names to choose from
Dim cmdText = "SELECT * FROM VistaProductos WHERE " & campo & " LIKE #valor"
Dim adaptador As New OleDbDataAdapter(cmdText, conexion)
adaptador.SelectCommand.Parameters.Add("#valor", OleDbType.VarWChar).Value = "%" & valor & "%"
adaptador.Fill(dataset, tabla)
Return dataset

Update query issue in VB and Access

I'm trying to implement the change password module in a application in VB. The update query is having some issues
Private Sub cmdOK_Click()
Query = "Select * From Users Where LoginID='" & txtLoginID & "' and Password = '" & txtCuPassword & "'"
Set reSet = myCon.Execute(Query)
If (Not reSet.BOF) And (Not reSet.EOF) Then
Query1 = "UPDATE Users SET Password ='" & txtNewPassword & "' WHERE LoginID='" & txtLoginID & "'"
Set reSet = myCon.Execute(Query1)
When executed an error is thrown at UPDATE query, as syntax error.
So, if your code has a single quote in the txtNewPassword field, your query ends up something like this
Query = "UPDATE Users SET Password ='mypass'word' WHERE LoginID='123'"
and this, of course is a syntax error.
You could try to replace a single quote with a pair of single quotes
Query = "UPDATE Users SET [Password] ='" & Replace(txtNewPassword, "'", "''") & "' WHERE ....
But remember that this code is open wide to SQL Injection. You should use parametrized queries also if it is not really easy to do that in VB6. Also, as pointed out by HansUp in its comment, you need to enclose the reserved word Password with square brackets
Why should I use Parameters instead of putting values into my SQL string

Using variables instead of objects

I used this line
.RecordSource = "select * from tblpersonal where empid like '" & Me.lblIDNumber.Caption & "*'"
...my question is, what if I use a variable (varIDNumber) instead of object (lblIDNumber), what would be the syntax? I am using VB6.0
You didn't mention txtIDNumber in the code -- you mentioned lblIDNumber. I assume you mean for those two to be the same. In other words, the code you have at present should be something like this:
.RecordSource = "select * from tblpersonal where empid like '" & Me.txtIDNumber.Text & "*'"
So you are using the value of a text box in a form to populate the SQL query. Am I right so far?
And you are asking, what if I store the ID number in a variable rather than a text field? I agree, this is probably a step in the right direction.
So you might create a variable in the "General Declarations" section of the form using:
Dim idNumber As Integer
With the idea being to update the value of that variable each time the text field changes. Note: I am assuming that the "ID number" is an integer -- if not, you should use a String instead.
Now you need to update that variable when the text field changes. In the txtIDNumber_Change event, you will want to add code to convert the string txtIDNumber.Text into an Integer, and store it in idNumber. I forget the exact syntax, but I am guessing something like:
idNumber = Int(txtIDNumber.Text)
Finally, you can now use the idNumber variable in the SQL query rather than the text box:
.RecordSource = "select * from tblpersonal where empid like '" & idNumber & "*'"
Replace Me.lblIDNumber.Caption with varIDNumber
If you have a constant in the label and would prefer for the constant to be stored in a variable instead, create a Const in the form's code. Let's say the label has the text "43" in it.
In the general declarations section of the form, add the code:
Const idNumber As Integer = 43
Then, when constructing the query:
.RecordSource = "select * from tblpersonal where empid like '" & idNumber & "*'"
This will construct the query using the constant 43. I don't really see the point of this -- if you want the employee number to be something the user can type in, see my other answer.

Please Correct my SQL Syntax

I know that there's something wrong with my syntax... "select * from tblpayroll where empid = userid"
UserID is a variable...
apparently, it's your vb variable.
select * from tblpayroll where empid = '" & userid & "' "
use it this way, and it'll work
The text "select * from tblpayroll where empid = userid" will be sent through exactly as is to the SQL back end, the userid part will not be substituted. So, unless you have a userid column, you'll probably get an error. Even if you do have a userid column, the results won't be what you expect.
What you need to do depends on whether userid is a numeric or string value. For numerics, you can use:
"select * from tblpayroll where empid = " & CStr(userid)
This will first turn the numeric value into a string and check it as-is.
For string values, use:
"select * from tblpayroll where empid = '" & userid & "'"
This will simply surround the string with quotes to ensure a string comparison works. You need to be aware that this is a bad idea if userid has not been sanitised somehow - it may lead to SQL injection attacks. The art of fixing that is outside the scope of this particular question but it's worth keeping in mind.
What to do if your variable is numeric but the database field is a string is another matter. You can do it with CStr and zero-padding but, since it's an unlikely scenario, I haven't documented it here.

Resources