this my code
SqlStr = "Select Test From Tbl_Test Where Test ='" & TextBox1 & "'"
how add Like in Where Test and TextBox1 to TextBox1*?
SqlStr = "Select Test From Tbl_Test Where Test Like='" & TextBox1* & "'"
This code gives an error .
You need to remove the '=' and add appropriate '%'s (which refer to any number of any character) depending on your needs.
The resulting string should be like so:
Select Test From Tbl_Test Where Test Like '%yoursearchhere%'
e.g.
SqlStr = "Select Test From Tbl_Test Where Test Like '%" & TextBox1.Text & "%'"
For Reference:
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql?view=sql-server-ver15
Related
In my excel sheet "Progress Status" I have 2 columns, the first one contain the list of all the test cases that are including during my cycle and in the second column I want to get the latest status of the test case from an other sheet named "All run TestCases".
I tried using some excel function to get the latest date and time so that I can get the latest status of a test case but I didn't succeed because I don't have a deep knowledge of them, Can someone please help me with this.The picture shows how my two sheet look like.
Okay here is the answer. Be sure executionDate and executionTime columns are in the Date and Time format respectively. Create a new column as FinalTime with the following function =B3+C3. Apply this for the rest. Then you can use the following macro. You may need to check Tools > preferences in the VBA screen if OLEDB connection is clicked. I assumed your sheets' names as TestCases and ProgressStatus. And header of Test case name is changed as Test. You can either change them on your sheet or in macro.
Sub makro()
Dim deneme As String
Dim queryStr As String
Dim con As Object, rs As Object, sorgu$, a$
Set con = CreateObject("adodb.connection")
Set rs = CreateObject("adodb.recordset")
con.Open "provider=microsoft.ace.oledb.12.0;data source=" & _
ThisWorkbook.FullName & ";extended properties=""Excel 12.0;hdr=yes"""
queryStr = "Select u.[Test]" & _
",u.[Status] " & _
"From [TestCases$] As u " & _
"Inner Join ( " & _
"Select [Test] " & _
",max(FinalTime) as [LastDate] " & _
"From [TestCases$] " & _
"Group By [Test]) As [q] " & _
"On u.Test = q.Test " & _
" And u.FinalTime = q.LastDate"
Set rs = con.Execute(queryStr)
Sheets("ProgressStatus").Range("A2").CopyFromRecordset rs
Set rs = Nothing
Set con = Nothing
End Sub
Here is the TestCases and ProgressStatus-with results- sheets I worked on.
I have the following vba query that works fine if there are no blank records in a particular field that contains dates. The error occurs when a blank exists in a particular record.
What am I trying to do?: extract a count out of my database between a date range. The startdate and enddate are cell references formatted as "MM/DD/YYYY" and the datebase field containing the dates are formatted as Date/Time, "short date".
query that works if my field column doesnt contain any blanks:
Dim startdate As Date
Dim enddate As Date
strSql = "SELECT Count(*) FROM tablename WHERE datevalue(Date_field_name) >= " & Format(startdate, "\#mm-dd-yyyy\#") & "AND datevalue(Date_field_name) <= " & Format(enddate, "\#mm-dd-yyyy\#")
I tried adding IS NOT NULL and that doesnt work:(
strSql = "SELECT Count(*) FROM tablename WHERE ANOTHER_Field_Name IS NOT NULL AND datevalue(Date_field_name) >= " & Format(startdate, "\#mm-dd-yyyy\#") & "AND datevalue(Date_field_name) <= " & Format(enddate, "\#mm-dd-yyyy\#")
help me pls!! This is driving me mad.
EDIT The complete code:
Public Sub counter()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Dim myCounter As Variant
Dim startdate As Date
Dim enddate As Date
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=Data.mdb"
strSql = "SELECT Count(*) FROM tablename WHERE datevalue(Date_field_name) >= " & Format(startdate, "\#mm-dd-yyyy\#") & "AND datevalue(Date_field_name) <= " & Format(enddate, "\#mm-dd-yyyy\#")
cn.Open strConnection
'Set rs = cn.Execute(strSql)
While (rs.EOF = False)
If (Not IsNull(rs(Sent_To_Tech_Date).Value)) Then
myCounter = myCounter + 1
End If
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
I generally see this kind of situation handled with a NZ function so that the field is just never left blank. So something like this:
strSql = "SELECT Count(*) FROM tablename WHERE datevalue(Nz(Date_field_name,"01-01-1969")) >= " & Format(startdate, "\#mm-dd-yyyy\#") & "AND datevalue(Nz(Date_field_name,"01-01-1969")) <= " & Format(enddate, "\#mm-dd-yyyy\#")
This also goes off of the assumption that you are just showing some stripped down code because you declare you variables then run a query without ever changing those variables to be a date.
The "01-01-1969" date should work for what you are looking for but if not adjust accordingly. Also my freehand SQL isn't amazing so some syntax might be a little off.
Correction on code:
strSql = "SELECT Count(*) FROM tablename WHERE datevalue(IIf(IsNull(Date_field_name),"01-01-1969", Date_Field_Name)) >= " & Format(startdate, "\#mm-dd-yyyy\#") & " AND datevalue(IIf(IsNull(Date_field_name),"01-01-1969", Date_Field_Name)) <= " & Format(enddate, "\#mm-dd-yyyy\#")
And if this doesn't suit your fancy if you take a look here: http://www.w3schools.com/sql/sql_isnull.asp There are other alternative ways to deal with nulls.
Round three, I think the Null idea was a red herring, pretty sure it is a lot of the un-needed formatting and that the "Format" part wasn't actually setting it to a date so it wouldn't do the comparison properly. Try out:
strSql = "SELECT Count(*) FROM tablename WHERE Date_field_name >= #" & startdate & "# AND Date_Field_Name <= #" & enddate & “#”
If your enddate and startdate are going to come in a non-date format then use
strSql = "SELECT Count(*) FROM tablename WHERE Date_field_name >= #" & Format(startdate,"\#mm-dd-yyyy\#") & "# AND Date_Field_Name <= #" & Format(enddate,"\#mm-dd-yyyy\#") & “#”
There is most likely a proper way to do this within the query string, but I haven't run across it. For this type of situation, I do it in two steps:
Instead of running a Count query, I will run a standard SELECT query to return all the records in the date range of interest.
Then I will loop through all the items in the recordset, discarding any that are null, and counting the rest.
While (myRecordSet.EOF = False)
If (Not IsNull(myRecordSet(Date_field_name).Value)) Then
myCounter = myCounter + 1
End If
myRecordSet.MoveNext
Wend
This is not the optimal way to do this in my opinion, but I have used it in the past and I know that it works.
I would like to connect to my Access tables using VBA. I want to be able to type in a purchase order number, and reference that value in a query to the Access table. I want to print the results of that query to my Excel worksheet. This is what I have so far.. any ideas?
Sub CommandButton1_Click()
Dim myValue As Variant
myValue = InputBox("Enter Purchase Order Number:")
Range("A1").Value = myValue
Call ADO_Conn(myValue)
End Sub
Sub ADO_Conn(myValue)
Dim conn As New Connection
Dim rstAnswer As New ADODB.Recordset
Dim connected As Boolean
Dim RootPath, DBPath As String
Dim tempString As String
connected = False
RootPath = "Z:\BSD Internship Program\FY14 Intern Files\John Jameson\Vouchers"
DBPath = RootPath & "Acquisition Support Datamart Build 9.11-03.accdb"
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= Z:\BSD Internship Program\FY14 Intern Files\John Jameson\Vouchers\Acquisition Support Datamart 9.1103.accdb;"
connected = True
rstAnswer.Open "SELECT VW_PUB_PURCHASE_ORDER.PO_NO FROM VW_PUB_PURCHASE_ORDER " & _
"WHERE VW_PUB_PURCHASE_ORDER.PO_NO = ' " & myValue & " ';", conn, adOpenKeyset, adLockOptimistic
Do Until rstAnswer.EOF
tempString = CStr(rstAnswer!VW_PUB_PURCHASE_ORDER)
Application.ActiveWorkbook.Worksheets("Sheet1").Range("A5").Value = tempString
rstAnswer.MoveNext
Loop
rstAnswer.Close
conn.Close
connected = False
End Sub
A couple of things about your initial query:
rstAnswer.Open "SELECT VW_PUB_PURCHASE_ORDER.PO_NO FROM VW_PUB_PURCHASE_ORDER " & _
"WHERE VW_PUB_PURCHASE_ORDER.PO_NO = ' " & myValue & " ';", conn, adOpenKeyset, adLockOptimistic
You are searching only for PO_NO in this query, so that is the only value that will return. If you want more than just that data (as I assume you might), then you want this:
rstAnswer.Open "SELECT * FROM VW_PUB_PURCHASE_ORDER " & _
"WHERE VW_PUB_PURCHASE_ORDER.PO_NO = ' " & myValue & " ';", conn, adOpenKeyset, adLockOptimistic
... where the asterisk means "all".
In addition, this bit concerns me:
' " & myValue & " '
You are adding leading and trailing blanks to your search term. This may or may not be what you want, but I assume that you do not want this. You probably want:
'" & myValue & "'
And if your PO_NO is a numeric value, you need to omit the apostrophes:
" & myValue & "
Lastly, I don't think you want to loop at all. The SELECT query will return all the results without requiring you to iterate rows. Maybe you should try getting rid of your "do" loop and using this instead:
Worksheets("Sheet1").Range("A5").CopyFromRecordset rstAnswer
Your query values will then be dropped into a dynamic range starting at the designated sheet & cell.
I didn't test the code so I might not have caught everything, but those jumped out at me.
Hope that helps!
Nate
I am writing an sql statement for an access database that will return a unique value regardless of the inputs. I am using this code however I am getting a type mismatch on the execute statement.
strSQL = "SELECT FilePath " _
& "FROM ToolFiles " _
& "WHERE Project_Num = '" & theSelectedProj & "'" _
& "AND Tool_Name = '" & theSelectedProjName & "'"
filePath = cn.Execute(strSQL)
Is there a way to return a string from an sql statement?
Thanks
The quick answer is No. The ADO Execute() method returns a recordset object which you will need to read into your string variable. Something like this should do it:
Dim rs As ADODB.Recordset
....
Set rs = cn.Execute(strSQL)
If Not (rs Is Nothing) Then
With rs
If Not (.BOF) And Not (.EOF) Then
strFilePath = Format$(.Fields(1).Value)
End If
End With
End If
I am trying to pull data from an ACD call data system, Nortel Contact Center 6.0 to be exact, and if you use that particular system what I am trying to capture is the daily call by call data. However when I use this code
(sCW is a common word string that equals eCallByCallStat and
sDate is
dDate = Format(Month(deffDate) & "/" & iStartDay & "/" & Year(deffDate), "mm/dd/yyyy")
sDate = Format(dDate, "yyyymmdd")
)
sSql = ""
sConn = "ODBC;DSN=Aus1S002;UID=somevaliduser;PWD=avalidpassword;SRVR=Thecorrectserver;DB=blue"
sSql = "SELECT " & sCW & sDate & ".Timestamp, "
sSql = sSql & sCW & sDate & ".CallEvent, "
sSql = sSql & sCW & sDate & ".CallEventName, "
sSql = sSql & sCW & sDate & ".CallID, "
sSql = sSql & sCW & sDate & ".TelsetLoginID, "
sSql = sSql & sCW & sDate & ".AssociatedData, "
sSql = sSql & sCW & sDate & ".Destination, "
sSql = sSql & sCW & sDate & ".EventData, "
sSql = sSql & sCW & sDate & ".Source, "
sSql = sSql & sCW & sDate & ".Time " & vbCrLf
sSql = sSql & "FROM blue.dbo.eCallByCallStat" & sDate & " " & sCW & sDate & vbCrLf
sSql = sSql & " ORDER BY " & sCW & sDate & ".Timestamp"
Set oQT = ActiveSheet.QueryTables.Add(Connection:=sConn, Destination:=Range("A1"), Sql:=sSql)
oQT.Refresh BackgroundQuery:=False
Do While oQT.Refreshing = True
Loop"
When I run this I get an odd error message at oQT.Refresh BackgroundQuery:=False
Oddly enough it worked for a month or so then just died
# loopo
I actually added the "" to the connection string and actually have the user name and password hard coded into the query with out quotes, I have since removed them for clarity in the posting
The error I recieve is
Run-time error '-2147417848(80010108)':
Method 'Refresh" of Object "_QueryTable' Failed
Thanks for your input Kevin. The Database is never in a state where no one is accessing it, it is a Call Handling system that is on 24 x 7 and always connected to is clients. At least that is my understanding. If I do this manually through Excel I never get an error, or have any issues only when I am doing this via a macro does it give me issues which lead me to think that it was my code causing the issue.
I am connecting to the database via ODBC as recommended by the manuafacturer, but I wonder if they ever envisioned this sort of thing.
I will see if I can leverage this into a .NET project and see if that helps.
Seems like an error with the query itself...
If you can step through your code and post the contents of sSql, it would probably help troubleshoot...
When you go through it, be sure quotes are getting escaped properly.
Looks like your connection string has double quotes in it.
This could potentially be due to some parsing by the website
you should probably set sConn using "double double" quotes, as in:
sConn = "ODBC;DSN=Aus1S002;UID=""somevaliduser"";PWD=""avalidpassword"";SRVR=""Thecorrectserver"";DB=blue"
What is the actual error message you're getting?
In the FROM clause, are you trying to SELECT from 2 different tables, with the same name in different namespaces? (In which case I think they should be separated by a comma rather than a space)
Or is there supposed to be another '.' instead of the space in the FROM clause? Or is it an alias?
Do you need to specify the table for every field? why not just do:
SELECT Timestamp, CallEvent, ... ,Time
FROM blue.dbo.eCallByCallStat" & sDate & " ORDER BY Timestamp
First off, if you're connecting to a non-generic database (SQL Server, Oracle, etc.), try using a database connection that's specific to it.
Secondly, since you said this error comes and goes, can you test whether it still happens when no one else is accessing the system? Perhaps it is an issue with certain rows being locked while your query is trying to read them...
Third, either switch to a different reporting method or find a different way to get the data. There are limits to this type of call within Excel. While, yes, it certainly does allow you to connect to databases and pull in data, you may find it falling short if you're working with large sets of data, complex queries, or finicky database connections.
I start by deleting the contents of sSQL with sSql=""
after that, because the query is run in a for loop I build the query in each of the next lines, each line builds on the previous line, I made it that way so it would be easier to edit and understand by the next guy.
After running through the sSQL looks like this
sSQL=SELECT eCallByCallStat20081001.Timestamp, eCallByCallStat20081001.CallEvent,
eCallByCallStat20081001.CallEventName, eCallByCallStat20081001.CallID,
eCallByCallStat20081001.TelsetLoginID, eCallByCallStat20081001.AssociatedData,
eCallByCallStat20081001.Destination, eCallByCallStat20081001.EventData,
eCallByCallStat20081001.Source, eCallByCallStat20081001.Time FROM
blue.dbo.eCallByCallStat20081001 eCallByCallStat20081001 ORDER BY
eCallByCallStat20081001.Timestamp
I was having this same issue when trying to refresh a Query.
For some reason that I don't know. When refering to a QueryTable object the refresh only works the first time you run the vba code. If you run it again the runtime error will prompt Run-time error '-2147217842(80040e4e): Method 'Refresh' of object '_QueryTable' failed occurs
This is an example of a Query refresh that fails.
Ws.ListObjects("TableName").QueryTable.Refresh BackgroundQuery:=False
Here is the solution found.
ThisWorkbook.Connections("ConnectionName").Refresh
If someone knows the reason why the refresh method of the QueryTable object fails. please let us know.