I cannot seem to get the following code to run. I appear to be having an issue with using sHostName in my Dlookup statement. What am I doing wrong?
Dim sHostName, LNum As String
sHostName = Environ$("computername")
LNum = DLookup("LineNumber", "tblLineNumber", "ComputerName = sHostName")
You need to concatenate the value of the sHostName variable.
DLookup("LineNumber", "tblLineNumber", "ComputerName = '" & sHostName & "'")
Related
I have two tables that are related, I'm trying to get data from the "parent" table using information in the "child" table. I'm attempting to use DLookup but I am getting a mismatch data type error.
I have a username variable available in the sub I am calling from and have created the below code:
Dim sqlstr As String
Dim placehldr As Long
username = Me.OpenArgs
placehldr = DLookup("userFullName", "tblUsers", "username='" & username & "'")
userFullName = DLookup("employeeFullName", "tblEmployees", "[ID]='&placehldr&'")
placehldr looks up according to a username the userFullName field which was created with lookup wizard so that users can look up the employee. This returns the autoID number from the first table tblEmployees. I have tried this using placehldr as long, integer, and string, and I have tried placing apostrophes as if it were a string or integer, I have also tried mixing these and using string apostrophes with int/long etc. It always returns the same mismatch type error on the second DLookup. Any help would be appreciated.
Dim sqlstr As String
Dim placehldr As Long
username = Me.OpenArgs
placehldr = DLookup("userFullName", "tblUsers", "username='" & username & "'")
userFullName = DLookup("employeeFullName", "tblEmployees", "[ID]=" & placehldr)
Per #dbmitch this worked correctly.
I have a project which is linked with a MDB file. I need to filter records of a table based on a condition, and both "field name" and the value or conditions should be passed to a Sub via variables. The select statement doesn't work. Did I miss something?
Dim Result() As DataRow
Dim strField As String = "asset_code"
Dim dblValue As Double = 3
Dim tblName as Datatable = AssetsDataSet.Assets
Result = tblName.Select(" '" & strField & "' = '" & dblValue& "' ")
I suspect that you need to loose the single quotes around the field name and as the data because it looks like it is numeric:
Result = tblName.Select(strField & " = " & cstr(dblValue) )
With string data you need to use a function:
Result = tblName.Select("textfield = " & cSQL(StringData) )
Function cSQL(psTextData As String) As String
' Replace any single quotes to be 2 single quotes
Return "'" + Replace(psTextData, "'", "''") + "'"
End Function
I am building a MS Access database and I cannot find a solution to my issue anywhere. All I want to do is trigger an update to my table using SQL code upon clicking a button, however, each time I try to run this code I get the error: "Run time error 3061, Too few parameters. Expected 1". The naming of all the tables and fields I call in my SQL code is correct. I copy/pasted the SQL string from my debug print into a query builder and it worked without issue. My code is:
Private Sub cmdAddRev_Click()
Dim compNum As String
Dim docPath As String
Dim filePath As String
Dim lastRev As Integer
Dim updateRev As Integer
Dim sqlStr As String
compNum = Me.cboRevSelection.Value
docPath = Me.tboRevDocLoc.Value
filePath = Me.tboRevFileLoc.Value
lastRev = DLookup("numLastRev", "tblComponents", "num = [Forms]![frmRevisor]![cboRevSelection]")
updateRev = lastRev + 1
sqlStr = " UPDATE tblComponents "
sqlStr = sqlStr & " SET numLastRev = " & updateRev
sqlStr = sqlStr & " WHERE num = [Forms]![frmRevisor]![cboRevSelection] "
CurrentDb.Execute (sqlStr) 'this line is flagged when the error happens
Debug.Print sqlStr
End Sub
Change this line:
sqlStr = sqlStr & " WHERE num = [Forms]![frmRevisor]![cboRevSelection] "
to this:
sqlStr = sqlStr & " WHERE num = '" & [Forms]![frmRevisor]![cboRevSelection] & "'"
SQL from VBA, doesn't like parameters. Always use your references outside of the quotes, so that the query going to the execute already has values in it. (although using a parametized query would be better still...)
You can't reference a form when executing SQL via VBA. There are several options. Set a tempvar to the desired value and reference the tempvar in the SQL or create a public function referencing the form and use the function in the SQL
Public Function RevSelection()
RevSelection = [Forms]![frmRevisor]![cboRevSelection]
End Function
Then use
sqlStr = sqlStr & " WHERE num = RevSelection()"
or, the simplest, reference it as a value.
sqlStr = sqlStr & " WHERE num =" & [Forms]![frmRevisor]![cboRevSelection]
I'm using a query to pull data from an SQL database, at times the last dropdown im using to get the record i'm looking for has a single quote, when it does I get the following error: Incorrect syntax near 's'. Unclosed quotation mark after the character string
This is the code I have:
Using objcommand As New SqlCommand("", G3SqlConnection)
Dim DS01 As String = DDLDS01.SelectedItem.Text
Dim State As String = DDLState.SelectedItem.Text
Dim Council As String = DDLCouncil.SelectedItem.Text
Dim Local As String = DDLLocal.SelectedItem.Text
Dim objParam As SqlParameter
Dim objDataReader As SqlDataReader
Dim strSelect As String = "SELECT * " & _
"FROM ConstitutionsDAT " & _
"WHERE DS01 = '" & DS01 & "' AND STATE = '" & State & "' AND COUNCIL = '" & Council & "' AND LOCAL = '" & Local & "' AND JURISDICTION = '" & DDLJurisdiction.SelectedItem.Text & "' "
strSelect.ToString.Replace("'", "''")
objcommand.CommandType = CommandType.Text
objcommand.CommandText = strSelect
Try
objDataReader = objcommand.ExecuteReader
DDLJurisdiction.Items.Add("")
While objDataReader.Read()
If Not IsDBNull(objDataReader("SUBUNIT")) Then
txtSubUnit.Text = (objDataReader("SUBUNIT"))
End If
If Not IsDBNull(objDataReader("DS02")) Then
lblDS02.Text = (objDataReader("DS02"))
End If
If Not IsDBNull(objDataReader("LEGISLATIVE_DISTRICT")) Then
txtALD.Text = (objDataReader("LEGISLATIVE_DISTRICT"))
End If
If Not IsDBNull(objDataReader("REGION")) Then
txtRegion.Text = (objDataReader("REGION"))
End If
If DDLState.SelectedItem.Text <> "OTHER" Then
If Not IsDBNull(objDataReader("UNIT_CODE")) Then
txtUnitCode.Text = (objDataReader("UNIT_CODE"))
End If
End If
End While
objDataReader.Close()
Catch objError As Exception
OutError.Text = "Error: " & objError.Message & objError.Source
Exit Sub
End Try
End Using
Not all records contain a single quote, only some, so i'd need something that would work if a single quote is present or not.
Thanks.
Your problem is this line here:
strSelect.ToString.Replace("'", "''")
This is changing your WHERE clause from something like
WHERE DS01 = 'asdf' AND ...
To:
WHERE DS01 = ''asdf'' AND ...
You need to do the replace on the individual values in the where clause, not on the whole select statement.
What you should really be doing is using a parameterized query instead.
Update: added same link as aquinas because it's a good link
Use parameterized queries, and only EVER use parameterized queries. See: How do I create a parameterized SQL query? Why Should I?
Was wondering how can we put an SQL statement in a String Variable?
Example:
Dim sqlQuery as String, qHolder as String
sqlQuery = "SELECT ID.table from table WHERE ID ='" userInputTextBox "'"
Whenever i do the above statement using either OpernRecordset() or RecordSource it gives me a bug. Can you give an example on how we do this, so we can use the value of sqlQuery for comparison for example
if(sqlQuery = userInputTextBox)then
MSgBox(" Match Found " )
Else
MsgBox("No Match Found")
Big Thanks in Advance.
Use the string concatenation operator (&).
sqlQuery = "SELECT ID.table from table WHERE ID ='" & userInputTextBox & "'"
Otherwise, it's a syntax error.
UPDATE
To get the value of ID.table into a string, use the Fields property of the Recordset:
Dim s As String
' by index
s = MyRec.Fields(0)
' or by name
s = MyRec.Fields("ID.table")