Create Temp Tables from Excel VBA (1 Viewer)

reggiete

Registered User.
Local time
Today, 15:44
Joined
Nov 28, 2015
Messages
56
Hello All,

I am just try create a temp table from excel VBA. Below is the code i have which works for a select statement. But i want to create a temp table.

'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=Test;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=test;Use Encryption for Data=False;Tag with column collation when possible=false;Initial Catalog=test"

'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900


'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT Top 10 * FROM TicketHistory Where DateTime>'2017-01-01' Order By DateTime Asc"

'Performs the actual query
rst.Open StrQuery, cnn

For iCols = 0 To rst.Fields.Count - 1
Worksheets("Sheet1").Cells(1, iCols + 1).Value = rst.Fields(iCols).Name
Next


'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub


Create temp table code
Create Table #FraudMailFlow (
TicketHistoryID varchar(255), TicketID varchar(255), AgentAssigned varchar(255), MonthYear varchar(255), ActionTaken varchar(255), Status varchar(255), Mailbox varchar(255), TicketBucket varchar(255), DateTime varchar(255))
 

NauticalGent

Ignore List Poster Boy
Local time
Today, 18:44
Joined
Apr 27, 2015
Messages
6,321
Good morning. If the Excel file is a current document that gets updated, a more efficient option would be to link the Excel file and then if temp tables were needed (I can't see why the would be) you could use stored Make Table querys to accomplish that.

Good luck!
 

Users who are viewing this thread

Top Bottom