【问】

hi

I have inherited a few spreadsheet that import data from Access onto a tabbed excel sheet.... I am finding this a bit painful.

Is there anyway to code it so that when the Excel spreadsheet opens it looks up the database and runs a query and dumps data onto a tab in code?

As this External toolbar query is a bit time consuming when I have 20 odd spreadsheets and 2 data queries per spreadsheet

cheers George

Am using Access 2000 and Excel 2000

 

【答】

It is quite easy to do that kind of thing using ADO code, but I don't know if it will be better/worse than Hack's suggestion.

All you need to do is open a connection to the database, and load a recordset, then basically "paste" into Excel using CopyFromRecordset, eg:
Code:
 
Dim objConn as ADODB.Connection
Dim objRS as ADODB.Recordset
Dim strSQL as String
 Set objCN = New ADODB.Connection
 objConn.Open "your connection string"
  Set objRS = New ADODB.Recordset
  strSQL = "SELECT Field1 FROM table1"
  objRs.Open strSQL, objConn, adOpenForwardOnly, adLockReadOnly, adCmdText
  WorkSheets("Sheet1").Range("A1").CopyFromRecordset
  objRS.Close
  Set objRS = Nothing
  objConn.Close
  Set objConn = Nothing
Untested, but should work if you just change the highlighted parts to suit your needs - see the "connection strings" link in my signature for what you need for the first one.