How to add time stamp in macro from selected excel sheet cells - sql

My vba code pulls data of last "11" hours from Database.
I want to pull data of my own time like "between (1/4/19 1:30 & 13/4/19 1:30)".Also want to add the data in sheet 1 like a table.
May i know how to add this custom time & make it a table using macro code.
Option Explicit
Sub DbConnection()
' NA Query connection with DB
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strConn As String
Dim mssql As String
strConn = "Driver={Redshift (x86)};Server=abc;Database=xyz;UID=abc;PWD=12345; Port=1234"
cn.Open strConn
cn.CommandTimeout = 60
mssql = "(using this line in SQL query here)"
where review_completed_timestamp_utc::TIMESTAMP > current_timestamp - interval'11 hour'
rs.Open mssql, cn
Sheets(1).Range("A2").CopyFromRecordset rs
End Sub

For the SQL part, since you didn't provide the names, you can do somenthing like this:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

Related

VBA SQL pulled data coming back as empty

I'm pulling into Excel VBA from a SQL ADODB Connection and it seems that some fields are coming back as empty that have values in SQL. I'm very green in VBA (just diving back into a legacy application to try and migrate everything to SQL Database storage instead of CSVs)
Here's an example of the value return (just a " where we should have "Sample Data | QRSTE/ S179399")
The code to pull:
Sub GetDFInfoByDf(recordID As String, connectionString as String)
Dim connectionString As String
connectionString = connectionString
Dim command As String
command = "Select * FROM data_table WHERE id = '" & recordID & "'"
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open connectionString
rs.CursorLocation = adUseClient
rs.CursorType = adOpenStatic
rs.LockType = adLockBatchOptimistic
Set rs = conn.Execute(command)
Dim rsMatrix As Variant
rsMatrix = rs.GetRows(1)
If IsNull(rs) Then
'rs is null
MsgBox "Pulled recordset is null"
Else
Call FillObjValuesFromRecordSet(rs)
End If
I see that we have a somewhat special character in there (|)
In terms of any SQL Encoding configurations: It's most likely UTF-8. I would think that I have to convert that to ANSI either in VBA or on the SQL side, but have been running in circles to try and figure that out.
Note that this field is NVARCHAR in SQL
Any ideas on how to handle this? Documentation is very sparse on the subject, from what I've seen.
Thanks!
Things I've Tried:
Adding Session Mode=ANSI; to the connection string
Expected Outcome:
-SQL stores the varchar "Sample Data | QRSTE/ S179399" (no quotes in the field)
-I'm expecting my Select to return that exact varchar/string value instead of the return in the image (")
Solution:
My SQL table columns with varchar(max) or nvarchar(max) were not able to translate back.
My initial table had larger-than-needed sizes, so altering those columns to varchar(8000) and nvarchar(4000) fixed the issue!
Thanks

Excel VBA ADODB - How to populate data based on an excel column values directly from SQL database without copying data into excel sheet

I'm running the following code for appending the data into columns B to G. My data is in Snowflake datawarehouse. The data is in millions so I cannot copy it into excel sheet first.
Option Explicit
Sub GetData()
Dim rs as ADODB.Recordset
Dim cn as ADODB.Connection
Dim connstr as String
Dim sqlstr as String
Set cn = New ADODB.Connection
cn.ConnectionString = DSNdetails.connstr
'DSNdetails is a module that holds DSN, DBCName, Databasename,Uid and password
cn.Open connstr
cn.Execute "USE WAREHOUSE db_warehouse;"
sqlstr = "SELECT employee_num, name, address, email, phone_num FROM Company;"
Set rs = New ADODB.Recordset
rs.Open sqlstr, cn, adStateOpen, adLockReadOnly
Sheet1.Cells(2,1).CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
This code runs perfectly. However the issue starts when I add WHERE clause and IN operator.
A | B | C | D |
Employee_num | name | address | phone
123
234
456
and so on
So now my new query is as below and Table1 is column A (I have considered it as string as well but same error) User can enter employee_num in each row and no matter how many rows they enter the data should populate in columns B to G if that employee_num in column A exists in SQL/Snowflake database
sqlstr = "SELECT employee_num, name, address, phone_num FROM Company WHERE employee_num IN ('"& _
Join(Application.Transpose(Range("Table1[Employee_num]").Value),'",")&");"
the code when debugged shows points at
rs.Open sqlstr, cn, adStateOpen, adLockReadOnly
Edit: Now I have a new runtime error "ODBC driver does not support the requested properties"

How do you use VBA to make a form jump to the nearest future date in Access?

I'm trying to get an MS Access database to open a form either to today's date if it's in the date field in the database, or the nearest date in the future. I tried the code here, but it doesn't work. It just highlights the date field and goes to the first record instead of the nearest one in the future.
The Date field is WorshipDate and the table is wp_elements. (I am a pastor using this table to plan Sunday Worship).
Private Sub Form_Load()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String
Dim TheDate As Date
Set db = CurrentDb
strSQL = "SELECT TOP 1 * FROM wp_elements WHERE wp_elements.WorshipDate >= Date() ORDER BY wp_elements.WorshipDate;"
Set rst = db.OpenRecordset(strSQL)
TheDate = rst.Fields(0)
WorshipDate.SetFocus
DoCmd.FindRecord TheDate, , True, , True
Set rst = Nothing
Set db = Nothing
'DoCmd.RunCommand acCmdRecordsGoToLast
End Sub
I know the SQL code I included works because I am using it in a Python script that's working quite well.
What am I missing? Or is there some other, easier way to do this?
You should only require one line of code:
me.RecordSet.FindFirst "Date() >= WorshipDate"

Excel Vlookup against SQL database

I normally vlookup my data against a table (database) in another workbook. (Excel to Excel --that's normally everyone does).
Since my table (database) grows more than 1.4 million rows therefore I need to transfer it to SQL Table in MS SQL Database.
I cannot move regular excel files just for Vlookup to SQL.
How do I vlookup excel against SQL tables.
Any solution with visual basic OR TSQL to fulfill requirement.
thanks
Yes, obviously, the limitation is just over a million rows, so you can use a Power Pivot Table to connect to multiple CSV files, aggregate the date you need, even if the total number of rows is over a million, and consolidate everything in one worksheet.
See the links below for more ideas of how to do this.
https://powerpivotpro.com/2017/01/import-csv-files-folder-filenames-excel/
http://sfmagazine.com/post-entry/january-2016-excel-combining-many-csv-files/
https://support.office.com/en-us/article/create-a-pivottable-with-an-external-data-source-db50d01d-2e1c-43bd-bfb5-b76a818a927b
You would use the 'Where' clause!
Sub ImportFromSQLServer()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim RS As ADODB.Recordset
Set RS = New ADODB.Recordset
Server_Name = "your_server_name_here"
Database_Name = "your_DB_name_here"
'User_ID = "******"
'Password = "****"
SQLStr = "select * from dbo.TBL Where EMPID = '2'" 'and PostingDate = '2006-06-08'"
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & ";"
'& ";Uid=" & User_ID & ";Pwd=" & Password & ";"
RS.Open SQLStr, Cn, adOpenStatic
With Worksheets("Sheet1").Range("A1")
.ClearContents
.CopyFromRecordset RS
End With
RS.Close
Set RS = Nothing
Cn.Close
Set Cn = Nothing
End Sub
Yes, you should be able to do that:
googling "excel connect to sql server" brings the result (description how to connect to a sql data source, to long to cite it here)
https://support.office.com/en-us/article/connect-a-sql-server-database-to-your-workbook-power-query-22c39d8d-5b60-4d7e-9d4b-ce6680d43bad
Then, when you have the connection, write your own lookup function in VBA, doing whatever you like.

Excel VBA - Get Data from SQL based of Cell range values

I've been tasked to get data from a SQL DB based off the values in Column A Row 3 onwards.
Example of Excel Sheet:
ITEM | QTY TO PICK | QTY ON ORDER | Column 2 | Column 3 etc
PART 1 | 5 | <Data will be populated here>
PART 2 | 12 | <Data will be populated here>
This code runs through a Command Button.
The data pulled from SQL will be populated starting in C3 onwards.
However, my below code only returns one row at a time.
I know where I need to make changes, I just don't know what. After at least 2 hours googling, I'm thoroughly stumped.
ItemNumber = Range("A3").Value
I've tried amending to ("A3:A100").Value but I just get errors.
Full code below;
Private Sub CommandButton2_Click()
' Create a connection object.
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "Provider=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "server=<server name>;INITIAL CATALOG=<DB Name>;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cn.Open strConn
'
'
ActiveSheet.Range("C3:G10000").Clear ' clear out existing data
Dim ItemNumber As String
ItemNumber = Range("A3").Value
' Create a recordset object.
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
SQLStr = "Select * from vw_WorksOrder WHERE ITEMNO = " & ItemNumber & ""
rs.Open SQLStr, cn
' Copy the records into cell A1 on Sheet1.
Sheet4.Range("C3").CopyFromRecordset rs
' Tidy up
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
You could try building the SQL like so
"Select * from vw_WorksOrder WHERE ITEMNO in (" & _
join(application.transpose(range("a1:a5").Value),",") & ")"
or, for strings.
"Select * from vw_WorksOrder WHERE ITEMNO in ('" & _
join(application.transpose(range("a1:a5").Value),"','") & "')"
My advise is:
1.)
Create a table on SQL Server which contains parameters for your sql statement (itemnumber = 1)
2.)
Write a cycle which loops tru the ranges and adds values one by one to the table like:
i = 1
while cells(i,3).value <> ""
... Insert into temptable values (parameter1,parameter2, etc)
i = i+1
wend
3.)
Modify your sql statement for the recordset joining the table with the parameters and the data you would like to pull and paste that data.