Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Excel Query that returns nothing 1

Status
Not open for further replies.

par60056

Programmer
Jul 16, 2001
31
0
0
US
Does anybody know if there is a way to execute a series of sql commands from Excel? Everything that I have found requires a destination and that the query return data.
 
first in the project window, Tools/References menu enable
Microsoft Access 9.0 Object Library
and
Microsoft DAO 3.6 Object Library
(office 2000)

in a module call this main sub. The "apAcc.DoCmd.RunSQL strSql" row runs an sql (string) command yielded from a text file with the function (ReadSQLString) bellow. You can also use an sql string stored in a cell (worksheets(1).range("d2").value ...) or other.

You can get a recordset object with openrecordset function.

You must set db (and sql) path..

Sub main()
Dim strSql As String
Dim dbWrk As Database
Dim apAcc As New Access.Application

Dim rstWrk As DAO.Recordset

Set apAcc = CreateObject("Access.Application")
Call apAcc.OpenCurrentDatabase("D:\TEMP\dk.mdb", False)
Set dbWrk = apAcc.CurrentDb

'fsql2.sql contains 3 rows; "DELETE * FROM Table2" ...
strSql = ReadSQLString("d:\temp\", "fsql2.sql")
apAcc.DoCmd.RunSQL strSql

Set rstWrk = dbWrk.OpenRecordset("SELECT * FROM TABLE1")
rstWrk.MoveLast
rstWrk.MoveFirst
MsgBox rstWrk.RecordCount

End Sub

Public Function ReadSQLString(Path As String, FileName As String) As String

Const ForReading = 1, ForWriting = 2, ForAppending = 3
Dim fs, f

Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.OpenTextFile(Path + FileName, ForReading, TristateFalse)
SQLSTring = ""
Do While f.AtEndOfStream <> True
SQLSTring = SQLSTring + f.ReadLine + &quot; &quot;
'Debug.Print SQLSTring ' Print data to the Immediate window.Loop
Loop
f.Close
ReadSQLString = SQLSTring
End Function

[wiggle] ide
 
Thank you. This got me in the right direction. All I needed to do was reference the DAO class.

Then the following worked.


Dim mydbe As DBEngine
Dim mywks As Workspace
Dim mydb As Database

Set mydbe = New DBEngine
Set mywks = mydbe.CreateWorkspace(&quot;main&quot;, &quot;me&quot;, &quot;&quot;, _
dbUseODBC)
Set mydb = mywks.OpenDatabase(odbcSource, _
dbDriverComplete, False, myConnectString)

' Build big sql statement
'
' Run sql statement
mydb.Execute sqlString
mydb.Close
mywks.Close
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top