SQL and Excel

D

drinese18

I want to basically create a little form that takes an SQL statement and
querys the result to excel, I already have code that does that but i instead
have it so that you can type your query statement in a cell on the sheet, but
I don't want that anymore I want to be able to click a button and it brings
up an input box where I can input the SQL statement then just like how it
takes the statement from the cell I want it to take the statement from the
input box instead, see my code below:

Sub download_query()
On Error GoTo datapullerr
Dim wk As Workbook
Dim data As Worksheet, para As Worksheet
Dim Sql$
Set wk = ThisWorkbook
Set data = wk.Sheets("SheetName")

Dim wrkodbc As Workspace
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim r As Range
Dim ts As String
Set wrkodbc = CreateWorkspace("NewODBCWorkspace", _
"admin", "", dbUseODBC)
Set db = wrkodbc.OpenDatabase("ODBCNAME", , ,
"ODBC;DSN=DSNE;UID=UID;pwd=pwd;SERVER=SERVER;")
ts = ""
i = 3
Sql = data.Cells(2, 4)
Set rs = db.OpenRecordset(Sql, dbOpenSnapshot)


If rs.EOF Then
MsgBox "index value not available"
Else
Dim qt As QueryTable
data.Range("a3:bb60000").ClearContents ' empty sheet
Set qt = data.QueryTables.Add(rs, data.Range("a3"))
qt.AdjustColumnWidth = False ' qt need not adjust width
qt.BackgroundQuery = False ' dont run on background.
qt.PreserveFormatting = True
qt.RefreshStyle = xlOverwriteCells
qt.FieldNames = True
qt.Refresh
tmpstr = data.Name & "!" & qt.Name
qt.Delete ' rid of the querytable
' delete the name that is created is using query table
For Each n In wk.Names
If n.Name = tmpstr Then
n.Delete
Exit For
End If
Next n
End If
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing

Exit Sub
datapullerr:
MsgBox (" Download Error; Operation aborted ")
'rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
End Sub


Hope someone can help me with this,

Thank you
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top