Retrieve the latest status of a value by date and time - excel

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.

Related

Is there any way of automating certain query execution and storing the O/P of that query in a excel file?

I have around 80 queries which I execute on a daily basis for monitoring purpose. All of them being SELECT queries, we capture the mostly the counts. This is turning out to be a boring task that's just running the query and manually capturing the output in an excel file.
For example, these are my queries with their sample respective outputs:
Query#1: SELECT count(*) from table WHERE certain_condition = 'True'
OUTPUT: 985
Query#2: SELECT count(*) from another_table WHERE yet_another_condition = 'True'
OUTPUT: 365
…
Query#80: SELECT count(*) from another_table WHERE yet_another_condition = 'True'
OUTPUT: 578
My requirement is this:
Capture the output of these 80 queries and paste them in an excel file in a certain order.
In Excel, I'll already have a heading (condition) in a cell. So I want the output of each query to be mapped to a specific cell corresponding to the heading (condition).
Is there any way of automating this boring task, or am I stuck for eternity as a bot?
PS: I am using Toad for Oracle v 12.9.0.71 database
Like Tim was saying ADO is your best bet here. Lucky for you I just had to do this myself so hopefully this should work for you.
Sub SQLQuery(sqlServer As String, strDatabase As String, strQuery As String, _
exportLocation As Variant, strUserId As String, strPassword As String)
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Set conn = Nothing
Set rs = Nothing
'create the Connection and Recordset objects
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
'open the connection
conn.Open _
"Provider=SQLOLEDB;" & _
"Data Source=" & sqlServer & ";" & _
"Initial Catalog=" & strDatabase & ";" & _
"User ID=" & strUserId & ";" & _
"Password=" & strPassword & ";" & _
"Trusted_Connection=" & "True" & ";"
'execute
Set rs = conn.Execute(strQuery)
'check if data exists
If Not rs.EOF Then
'if so, copy to location
exportLocation.CopyFromRecordset rs
'close the recordset
rs.Close
End If
'clean up
conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
An example of using this subroutine:
Call SQLQuery( _
oSERVER, _
oDB, _
"SELECT count(*) from table WHERE certain_condition = 'True'", _
ThisWorkbook.Sheets("Sheet1").Cells(1, 1), _
oUSER, _
oPW)
Just for reference you will likely have to enable Microsoft ActiveX Data Objects 2.8 Library in your References for this to work.

Execute sql complex query through excel vba

Just to give you background of my work, i have to fetch data from MS Sql on daily basis and for that every time have to go to other server to run the query. Once the query is executed, have to paste into my common drive, which takes a lot time. ~55 mins to paste 5,00,000 row & 30 fields to common or to move file. In total 2 hours for execution & movement from one location to other.
To reduce this i would need your help to use the SQL queries through excel with the below things:
If possible,
Point1: Query will be stored in the text file in the common location
Point2: Query Parameter to be populate to get
Or
Point2:Range to be defined for parameter
If not possible above,
Query will be pasted into the code and parameter to be populated based on the above mentioned suggestion.
Connection type is windows authentication, it will work based on logged in users windows name.
This code will allow you to provide variables that you use within your SQL statement and put those into cells on a spreadsheet (In this case Cred2) and return the results on a separate sheet (Sheet2).
The first portion of the code establishes a connection with the SQL server.
The column Headers will be started in Row 2 and then the data will begin populating starting on row 3. I have used this to pull well over 100,000 records at a time and this works very quickly.
Private Sub CommandButton1_Click()
Dim cn As Object
Dim rs As Object
Dim strCon As String
Dim strSQL As String
strCon = "DRIVER=SQL Server;SERVER=ServerName;DATABASE=DBName;Trusted_Connection=True"
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
' if not a trusted connection you could replace top line of strCon with
strCon = "DRIVER=SQL Server; Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword"
' set up where you are getting your variables to include in the SQL statement
stat = Sheets("Cred2").Range("c7").Value
barg = Sheets("Cred2").Range("c10").Value
worksite = Sheets("Cred2").Range("c11").Value
' Construct SQL statement
strSQL = "select * " _
& " FROM tableName A , table2 B " _
& "WHERE A.[field1] = B.[field1] " _
& " and field1 like '" & stat & "'" _
& "and field2 like '" & barg & "'" _
& "and field3 like '" & worksite & "'" _
& " order by Field? "
' Build Record Set
Set rs = CreateObject("ADODB.RECORDSET")
rs.ActiveConnection = cn
rs.Open strSQL
' Display Data
For intColIndex = 0 To rs.Fields.Count - 1
Sheet2.Range("A2").Offset(0, intColIndex).Value = rs.Fields(intColIndex).name
Next
Sheet2.Range("A3").CopyFromRecordset rs
' Close Database
rs.Close
cn.Close
Set cn = Nothing
end sub

Using VBA to connect Access to Excel, will not output any records from Access

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

ADO query of date value in Excel returns string as formatted in worksheet

I'm trying to pull data from an Excel sheet using an ADO query. However, date values are being returned the way they're formatted on the worksheet, rather than the actual date value. For example, the value 8/12/1929 is formatted as 8/12/29, so the query is returning the string "8/12/29". This makes it hard to determine what the correct date is based on the recordset data alone, as the year could also be 2029 in this case.
Here's the code for the ADO query:
Function WorksheetRecordset(workbookPath As String, sheetName As String) As ADODB.Recordset
Dim objconnection As New ADODB.Connection
Dim objrecordset As New ADODB.Recordset
'On Error GoTo errHandler
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
objconnection.CommandTimeout = 99999999
objconnection.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & workbookPath & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"";"
objrecordset.Open "Select * FROM [" & sheetName & "$]", _
objconnection, adOpenStatic, adLockOptimistic, adCmdText
If objrecordset.EOF Then
Set WorksheetRecordset = Nothing
Exit Function
End If
Set WorksheetRecordset = objrecordset
On Error GoTo 0
Exit Function
errHandler:
Set WorksheetRecordset = Nothing
On Error GoTo 0
End Function
I'm fetching the value by using, e.g.
Sub getValue(rs as ADODB.Recordset)
Debug.Print rs.Fields(0).Value
End Sub
Part of the problem might be that the date values don't start until after several rows of text, so maybe when ADO detects the field type as text it only fetches the visible formatted value. Is there a way to retrieve the actual date value?
EDIT: Just realized that this is similar to this SO question that I previously asked: ADO is truncating Excel data. But I didn't get a satisfactory answer from that one, so I'll ask this one anyways.
Since you have 58 fields I think that the best thing is to build a string running the following code on the workbook that contains the data:
Dim rng as Range
Dim val as Variant, txt as String
Set rng = Worksheets("sheetName").Range("A3:BF3")
For Each val In rng.Value
txt = txt & "[" & val & "], "
Next val
Debug.Print txt
Then you copy the text from the Immediate window and paste in your code, like this:
Dim strFields as String, strSQL as String
strFields = 'Paste the text here
'Note the FROM clause modification
strSQL = "SELECT CDATE([myDate]), " & strFields & " FROM [" & sheetName & "$A3:BF]"
'...
objrecordset.Open strSQL, _
objconnection, adOpenStatic, adLockOptimistic, adCmdText
Note that the FROM clause has the form [sheet$A3:BF]. This specify the third row as the first row that contains data. More details in this question or in this link

Using ADODB in VBScript to find the number of rows in an Excel sheet?

I'm trying to use ADODB in VBScript to access an Excel file to find the number of rows in a given sheet that have data entered into them. My code so far displays everything on the sheet, but I'm not sure how I could count the rows or directly find the number of rows using a query. I want to use ADODB as it doesn't open the Excel file directly, but if this isn't the best way then how could I do it otherwise? Thanks.
Set adodb = CreateObject("ADODB.Connection")
adodb.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
"test.xls" & ";Extended Properties=""Excel 8.0;IMEX=1;" & _
"HDR=NO;" & """"
Set result = adodb.Execute("Select * from [Sheet1$]")
MsgBox result.GetString
result.Close
adodb.Close
Set adodb = Nothing
Set result = Nothing
Add a CursorLocation property for your Connection object.
Updated:
'result.CursorLocation = 3 'adUseClient
adodb.CursorLocation = 3 'adUseClient
Then you can get number of rows.
MsgBox result.RecordCount
I got this to work ok:
Sub testit()
Dim ad As New adodb.Connection
Dim result As New adodb.Recordset
ad.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=test.xls ;" & _
"Extended Properties=Excel 8.0;"
result.Open "Select count(*) FROM [Sheet1$]", _
ad, adOpenStatic, adLockOptimistic, adCmdText
Debug.Print "rows:" & result.GetString
result.Close
ad.Close
End Sub
(I changed your variable name adodb, as it seems to conflict).

Resources