I'm currently making an Excel function that connects to an SQL server and retrieves data as long as it matches the given criteria.
Public Function VehModelUnitsCount(VehModel As String, fran As String, Site As Integer, SaleType As String, StartDate, EndDate, New As Integer) As Variant
Application.Volatile
If adoCN Is Nothing Then Call SetUpConnection
Set adoRS = New ADODB.Recordset
EvoStartDate = Format(StartDate, "yyyy/mm/dd")
EvoEndDate = Format(EndDate, "yyyy/mm/dd")
strSQL = "SELECT COUNT(*) As RCOUNT FROM CARTYPES RIGHT OUTER JOIN CARS ON CARTYPES.Description = CARS.Type LEFT OUTER JOIN CARS2 ON CARS.[Stock Number] = CARS2.[Stock Number]" & Chr(13)
strSQL = strSQL & "WHERE (CARTYPES.NewSale = " & New & " )" & Chr(13)
strSQL = strSQL & "AND (CARTYPES.Franchise = '" & fran & "')" & Chr(13)
strSQL = strSQL & "AND (CARTYPES.Site = " & Site & ")" & Chr(13)
strSQL = strSQL & "AND (CARTYPES.SaleTypeDesc = '" & SaleType & "')" & Chr(13)
strSQL = strSQL & "AND (CARS2.InvoiceDate BETWEEN '" & StartDate & "' AND '" & EndDate & "')" & Chr(13)
strSQL = strSQL & "AND (CARS.Invoiced = '1')" & Chr(13)
Rem strSQL = strSQL & "AND (CARS.Model = '" & VehModel & "')" & Chr(13)
[THIS ONE] - strSQL = strSQL & "AND (CARS.Model CONTAINS '" & VehModel & "')" & Chr(13)
adoRS.Open strSQL, adoCN, adOpenForwardOnly, adLockReadOnly
VehModelUnitsCount = adoRS.Fields("RCOUNT").Value
adoRS.Close
End Function
The string marked with [THIS ONE] is the one I am struggling with, I need to find out whether or not the cell contains the given string, but apparently using 'CONTAINS' doesn't work.
Any help on completing this would be amazing.
Thank you.
You could try -
strSQL = strSQL & "AND (CARS.Model LIKE '%" & VehModel & "%')" & Chr(13)
Related
Here's my code:
strSQL = "UPDATE tblTransactions SET Verifier = '" & strUserName & "' WHERE PatientAccountNumber = '" & Me.PatientAccountNumber & "'"
strSQL = "UPDATE tblTransactions SET VerifierAssgnDate = #" & Date & "# WHERE PatientAccountNumber = '" & Me.PatientAccountNumber & "'"
"Verifier" updates fine, but "VerifierAssignDate" throws a "field not updateable" error. It's a DateTime field.
Thanks!
You can and should combine these (and VerifierAssgnDate was probably misspelled):
strSQL = "UPDATE tblTransactions " & _
"SET Verifier = '" & strUserName & "', VerifierAssignDate = Date() " & _
"WHERE PatientAccountNumber = '" & Me.PatientAccountNumber & "'"
Im getting a Data type mismatch in criteria expression.
This is an update button Im trying to implement.
Access_Num is the only number(data_type) here.
I'm using MSACCESS2007
Is it a good pracrice to make all data types in the database as text?
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
cn = New OleDbConnection(con)
cn.Open()
With cmd
.Connection = cn
.CommandText = "Update [Book] SET [Book_ID] = '" & TextBox1.Text & _
"', [Access_Num] = '" &Integer.Parse(TextBox2.Text) & _
"', [Title] = '" & TextBox3.Text & _
"', [Author] = '" & TextBox4.Text & _
"', [Publisher] = '" & TextBox5.Text & _
"', [Category] = '" & ComboBox1.Text & _
"', [Contents] = '" & TextBox7.Text & _
"', [Availability] = '" & ComboBox2.Text & "' WHERE [Access_Num] = '" & Integer.Parse(TextBox2.Text) & "'"
.ExecuteNonQuery()
End With
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
'cn.Close()
'cmd.Dispose()
MsgBox("Successfully Updated")
End Sub
Your problem is that you have string delimiters everywhere. Remove them for all fields that aren't strings:
With cmd
.Connection = cn
.CommandText = "Update [Book] SET [Book_ID] = '" & TextBox1.Text & _
"', [Access_Num] = " & Integer.Parse(TextBox2.Text) & _
", [Title] = '" & TextBox3.Text & _
"', [Author] = '" & TextBox4.Text & _
"', [Publisher] = '" & TextBox5.Text & _
"', [Category] = '" & ComboBox1.Text & _
"', [Contents] = '" & TextBox7.Text & _
"', [Availability] = '" & ComboBox2.Text & "' WHERE [Access_Num] = " & Integer.Parse(TextBox2.Text)
.ExecuteNonQuery()
End With
Note that a better way would be to use parameters for the query, since that also avoids SQL injection.
Is it a good pracrice to make all data types in the database as text?
No, certainly not! That's an awful practice. Data types should represent the data stored in the column, and be the smallest practical type to represent that data.
can anyone help me where am I doing wrong.. im building an update statement with multiple columns to update MSQL with VBA and values from Excel. heres my simple code, Im parsing variable in function to execute SQL command (I have a table name "People" and I have define all the column) below:
Function GetUpdateTextSQL(PIC As String,
Customer As String,
DOB As Date,
Rank As String,
Organization As String,
Status As String,
Gender As String,
Religion As String,
Hobby As String,
CreatedBy1 As String,
CreatedOn1 As Date,
ChangedBy1 As String,
ChangedOn1 As Date,
PeopleID As Integer) As String
SQLStr = _
"UPDATE People" & _
"SET PIC = " & _
"'" & PIC & "', Customer = '" & Customer & "'," & _
"DOB = '" & Format(DOB, "yyyy-mm-dd") & "', Rank = '" & Rank & "'," & _
"Organization = '" & Organization & "',Status = '" & Status & "', Gender = '" & Gender & "'," & _
"Religion = '" & Religion & "', Hobby = '" & Hobby & "'," & _
"CreatedBy = '" & CreatedBy1 & "', CreatedOn = '" & CreatedOn1 & "'," & _
"ChangedBy = '" & ChangedBy1 & "', ChangedOn = '" & ChangedOn1 & "'" & _
"WHERE PeopleID = & PeopleID &;"
GetUpdateTextSQL = SQLStr
//And here Im inserting and executing command below to get values from excel:
For Each r In Range("A45", Range("A45").End(xlDown))
CmdForSave.CommandText = _
GetUpdateTextSQL( _
r.Offset(0, 1).Value, r.Offset(0, 2).Value, _
r.Offset(0, 3).Value, _
r.Offset(0, 4).Value, r.Offset(0, 5).Value, _
r.Offset(0, 6).Value, r.Offset(0, 7).Value, _
r.Offset(0, 8).Value, r.Offset(0, 9).Value, _
r.Offset(0, 10).Value, r.Offset(0, 11).Value, _
r.Offset(0, 12).Value, r.Offset(0, 13).Value, _
r.Offset(0, 0).Value)
CmdForSave.Execute
Next r
The error I get is 'Incorrect Syntax near 'PIC'
What is wrong with my code? Iam using MS SQL Express (SQL 2012)
Thanks All,
I have figured it out why the problem is with space on the update SQL Statement.
The right statement using VBA (space before SET, space before WHERE):
SQLStr = _
"UPDATE People" & _
" SET PIC = '" & PIC & "', Customer = '" & Customer & "'" & _
" WHERE PeopleID = '" & PeopleID & "';"
I have 4 tables: Code_Product, Name_Product, Color_Product, Size_Product
And code:
Public Sub ExecuteQuery(query As String)
Dim command As New SqlCommand(query, connection)
command.ExecuteNonQuery()
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim updateQuery As String = "UPDATE tbl_Product SET Name_Product = '" & txtNameProduct.Text & "' , Color_Product = '" & txtColorProduct.Text & "', Size_Product = '" & txtSizeProduct.Text & "' where Kode_Produk= '" & txtKodeProduk.Text & "'"
ExecuteQuery(updateQuery)
MessageBox.Show("Data has been changed")
Notes: the code work.
But, the code changes all columns, and I just want to change only one column. How?
replace this line
Dim updateQuery As String = "UPDATE tbl_Product SET Name_Product = '" & txtNameProduct.Text & "' , Color_Product = '" & txtColorProduct.Text & "', Size_Product = '" & txtSizeProduct.Text & "' where Kode_Produk= '" & txtKodeProduk.Text & "'"
with this. Pass only that column which you want to update.
Dim updateQuery As String = "UPDATE tbl_Product SET Name_Product = '" & txtNameProduct.Text & "' where Kode_Produk= '" & txtKodeProduk.Text & "'"
I am opening an SQL Server Connection in EXCEL VBA and on the objMyCmd.Execute line when it is using the SQL script I am getting this error message:
"Run-time error '-2147217900 (80040e14)') Automation error"
I have reviewed other SO posts that seem to reference an issue with the connection string itself, but I don't believe that is the issue as I am able to pull the first few variables listed when eliminating the rest of the SQL script.
I have attempted to review the SQL code to see if I am using an incorrect format, or if the language is not written properly and I am not able to determine the issue. I am hoping with some Q & A we may notice something I have missed in how this is written? Please let me know if there is additional information I can provide, below is the code up to the point of error.
Sub SQL_GetAgentChart()
Dim dtDate As Date
Dim myTable As ListObject
Dim DataServer As String
Dim Database As String
Dim constring As String
DataServer = "GLSSQLMADP2"
Database = "PERF_MGMT_BWRSRV_PROD"
constring = "Driver={SQL Server};Server=" & DataServer & "; Database=" & Database & "; Trusted_Connection=yes"
Dim AVStartDate As Date
Dim AVEndDate As Date
Dim RepID As Long
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
Set myTable = Worksheets("Witness").ListObjects("tblWitness")
AVStartDate = DateValue("Mar 01, 2016")
AVEndDate = DateValue("Mar 31, 2016")
RepID = 2040
'Open Connection'
objMyConn.ConnectionString = constring
objMyConn.Open
'Set and Excecute SQL Command'
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = " " & _
"SELECT PERSN_XTRNL_ID_NR, SOURCE, LOGGINGTS, DD7, CUREREASON, CUREDATE, LNSTATUS " & _
"FROM TTB " & _
"WITH INCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN PERSONNEL P ON T.PERSONNELID = P.PERSONNELID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE T.PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 1 " & _
"AND DD7 > 0), OUTCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN AVAYA A ON T.UID = A.TTBUID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 0 " & _
"AND A.AVAYAGROUP IN ('15', '1A', '1B', '1C', '1D', '1E', '1F', '1G', '1H') " & _
"AND DD7 > 0) "
objMyCmd.CommandType = adCmdText
objMyCmd.Execute