I have the following microsoft access vba code I want to use to update a table called tb_users.
The table has 4 columns (Id, username,password,firstlogindate).
Dim db as database
Dim MySQL as string
Set db= currentdb
If isnull(firstlogindate) =true then
Mysql = Update tblusers set firstlogindate = date() where username =" & chr(34) & cbousername & chr(34)
Execute db.mysql
Endif
But I get the following error: [Expecting end of statement] with this line. Mysql = Update tblusers set firstlogindate = date() where username =" & chr(34) & cbousername & chr(34) highlighted in red.
What is wrong with the code?
Is there a better way of achieving the above?
You miss some quotes - or use single quotes:
Dim db as DAO.Database
Dim MySQL As String
Set db= CurrentDb
If IsNull(firstlogindate) = True Then
MySQL = "update tblusers set firstlogindate = date() where username = '" & cbousername & "'"
db.Execute MySQL
End If
Try this:
Mysql = "Update tblusers set firstlogindate = date() where username ='" & cbousername & "'"
db.Execute Mysql, dbFailOnError
Related
Current Situation
I have a database in MSSQL and currently it is able to link to excel the following way.
Excel table which is connected to MSSQL as follows
MSSQL table as below
Currently if I update my MSSQL table, excel table will update accordingly
What I need
I want the vice versa operation. Means whenever I update the excel table, MSSQL also needs to update. Is this possible?
I am able to do it correctly by using following code
Sub updateSqlFromExcel()
Dim cnn As ADODB.connection
Dim uSQL As String
Set cnn = New connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=myServer; " & _
"Initial Catalog=myDatabaseName;" & _
"User ID=username;" & _
"Password=password;" & _
"Trusted_Connection=No"
Set rngName = ActiveCell
cnn.Open cnnstr
excelId = ActiveCell.Value 'This is just an example
excelSeq = ActiveCell.Offset(0, 1).Value 'This is just an example
excelName = ActiveCell.Offset(0, 2).Value 'This is just an example
uSQL = "UPDATE myTableName SET Name = '" & excelName & "', Seq = '" & excelSeq & "' WHERE ID= '" & excelId & "' "
cnn.Execute uSQL
ActiveWorkbook.RefreshAll
MsgBox "Updated successfully. But please wait until background refresh finish before close excel", vbInformation, "Success"
cnn.Close
Set cnn = Nothing
End Sub
Please change myServer, myDatabaseName, username, passwordand myTableNameaccording to your settings in order for this macro to work. Also please add reference library Microsoft ActiveX Data Objects 2.8 Library. In order to add, press Alt+F11 and then goto Tools --> References. Scroll to Microsoft ActiveX Data Objects 2.8 Library and tick the checkbox. Press ok and you are ready to go.
I've been searching hard the past few days and have come across numerous examples that outline what I'm trying to do. However, I can't seem to get this working. I have a combobox that populates data (a company name) from a table when the form initializes. I then want to take the value chosen in the combo box and run another query to cross reference an id number in that same table.
Private Sub CommandButton1_Click()
Dim myCn As MyServer
Set myCn = New MyServer
Dim rs As ADODB.recordset
Set rs = New ADODB.recordset
Dim sqlStr As String
Dim CompField As String
'CompField = ComboBox1.Value
sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = '" & ComboBox1.Text & "'"
'sqlStr = "Select DISTINCT [company] FROM client;"
' sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = " & UserForm1.ComboBox1.Value & ";"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = " & UserForm1.ComboBox1.Text & ";"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = 'Company XYZ';"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE company = " & CompField & ""
rs.Open sqlStr, myCn.GetConnection, adLockOptimistic, adCmdText
MsgBox sqlStr
'MsgBox ComboBox1.Value
'MsgBox rs(0)
rs.Close
myCn.Shutdown
Set rs = Nothing
Set myCn = Nothing
End Sub
Currently with the combobox value encased in single quotes i get the entire sql string returned. If I remove the single quotes I get a syntax error referencing part of the combobox value. All other efforts have resulted in run-time errors that have led me nowhere.
I know my query works because I've tested it in SQL Studio and if I hard code a text value in this code I also get the Account ID I'm looking for. Not sure what I'm missing here.
Well I figured it out. I was expecting to be able to MsgBox the variable assigned to the SQL query and see my results. But it doesn't work that way. I had to use ADO GetString method for that and assign another variable. Oh and you were right about escaping, I had to add delimters to properly handle the ComboBox value in the query which ultimately looked like this
sqlStr = "SELECT DISTINCT [acct_no] FROM client WHERE [company] = " & Chr(39) & Me.ComboBox1.Value & Chr(39)
Thanks for your help on this
I use external data from an SQL query in excel to pull data onto a spreadsheet then the spreadsheet can be sent to one of my colleges in say the sales department and they can view the queried information.
I want to be able to have a cell that they can enter data into and press a refresh button.
So I need to do some thing like this:
SELECT Customer.CustomerCode, Customer.Name,
OrderHeader.OrderType, OrderHeader.OrderNumber
FROM Customer INNER JOIN
OrderHeader ON Customer.CustomerID = OrderHeader.CustomerID
WHERE (OrderHeader.OrderType = 2) AND (OrderHeader.OrderNumber = Range("A1").Value)
Not sure how or if this is possible and the reason I need to do this is because i'm going through lines from all the Quotes and if there is over 65536 then i'll have a problem.
This is what I have at the moment the SQL is different but that doesn't matter
The easiest way is to pull the values for the parameters into VBA, and then create the SQL statement as a string with the parameter values, and then populate the commandtext of the query.
Below is a basic example of the parameter in cell A1.
Sub RefreshQuery()
Dim OrderNo As String
Dim Sql As String
' Gets value from A1
OrderNo = Sheets("Sheet1").Range("A1").Value
'Creates SQL Statement
Sql = "SELECT Customer.CustomerCode, Customer.Name, " & _
"OrderHeader.OrderType , OrderHeader.OrderNumber " & _
"FROM Customer " & _
"INNER Join OrderHeader ON Customer.CustomerID = OrderHeader.CustomerID " & _
"WHERE (OrderHeader.OrderType = 2) And (OrderHeader.OrderNumber = " & OrderNo & ") "
With ActiveWorkbook.Connections(1).ODBCConnection
.CommandText = Sql
.Refresh
End With
End Sub
This assumes you have the query in Excel to begin with, and that it's the only query. Otherwise you'll have to define the name of the query as below:
With ActiveWorkbook.Connections("SalesQuery").ODBCConnection
I hope that helps :)
Further to #OWSam's example using ODBC, we can also use ADO to pull back query results from SQL Server. Using ADO, you cannot use windows verification and you will need the user to input their password somehow, to be able to run the query.
Personally I create a userform which has UserName and Password. Username pre-populated using Environ, and then they can type their password into the relevant TextBox.
Sub sqlQuery()
Dim rsConn As ADODB.Connection, rsData As ADODB.Recordset
Dim strSQL As String, winUserName As String, pwd As String
winUserName = UCase(Environ("username"))
pwd = "mypassword" 'password needed here.
strSQL = "SELECT * FROM mydatabase" 'query
Set rsConn = New ADODB.Connection
With rsConn
.ConnectionString = "Provider = sqloledb;" & _
"Data Source = [server name here];" & _
"Initial Catalog = [initial database];" & _
"Integrated Security=SSPI;" & _
"User ID = " & winUserName & ";" & _
"Password = " & pwd & ";"
.Open
End With
Set rsData = rsConn.Execute(strSQL)
Range("A1").CopyFromRecordset rsData
End Sub
Edit: You must go into references and turn on the Microsoft ActiveX Data Objects Recordset 6.0 library (or equivalent within your VBE).
I'm using this code to add a new column:
DataGridView1.Columns.Add("Test", "TesT")
but after saving and closing the project then I open it again the columns were deleted.
The question is how to save the columns to the access database.
If your just going to save the values, than you'd have to call them back up in order to fill the grid.
Sample code to insert into an access db.
Dim Cmd as New OLEDb.OleDbCommand
Dim oleConn as New OleDb.OleDbConnection
Dim strDataBase as String
strDataBase = "C:\Test.mdb"
'2007 connection string will work for 2003-2007 databases - change to 14.0 for 2010 etc
oleConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strDataBase & ";Jet OLEDB"
Cmd.Connection = oleConn
oleConn.Open()
Cmd.CommandText = "Insert into mytable ( Field1, Field2 ) values ( '" & "some Value" & "', '" & "some value" & "' )"
Cmd.ExcuteNonQuery
oleConn.Close()
I've searched high and low to resolve this one, but can't seem to fix it on my own. I'm new to classic ASP but a very long time PhP dev.
I'm getting
ADODB.Recordset error '800a0e78'
Operation is not allowed when the object is closed.
/sdd/fx_mlogin.asp, line 54
While logging in to the site i'm working on. The line's that's its referencing is:
Set rs = cmd.Execute
If RS.BOF or RS.EOF then
More relevant code:
Set cn = Server.CreateObject("ADODB.Connection")
cn.Open MM_ap_connect_STRING
Set cmd = Server.CreateObject("ADODB.Command")
Set cmd.ActiveConnection = cn
cmd.CommandText = "sd_member_login " & "'" & guid & "', " & """" & trim(user) & """, " & "'" & trim(pw) & "', " & "'" & uip & "', " & "'" & uagent & "', " & "'" & logintrack & "'"
Set rs = cmd.Execute
If rs.BOF or rs.EOF then
The kicker is that the site worked before and we're moving hosts. The connection is apparently working, but I'm suspicious that its still the issue. My connection string is
MM_ap_connect_STRING = "Provider=SQLOLEDB;Data source=sql2103.shared-servers.com,1087;Initial catalog=database;User Id=username;Password=password;"
But obviously with the username, password, and database fields filled in. I'm also connecting to a SQL 2005 database. Any help would be appreciated! Let me know if I need to provide any more information.
Try adding the T-SQL line:
SET NOCOUNT ON
to the top of the SQL being executed.
I had this exact issue. For me the answer was my stored procedure had an owner of DBO. Which my user for the previous database was set to DBO. On our destination database there was a different DBO, which caused a execute permissions issue. Just changed my db user to DBO and it's working now. Hope that helps.