Vous êtes sur la page 1sur 8

Connectin ngSQLandEx xcel(Prof.Lo orinHitt) (Firstdraf ft:1/1/2011) ) Thereare eanumberof fwaysinwhic chExcelcaninteractwitha aSQLdataba ase.

Thisbrief ftutorialcove ers twoofthe em: 1)Youcan nimportthedatausingtheDataGet tExternalDat tatoolsusing gtheribbonin nterface.Thisis goodifyo oujustwantt toloadanent tiredatabasetablefromSQ QLintoanEx xcelSheet. 2)Youcan nwriteVBAp programsthat texecuteque eriesandretu urnresultsag gainstanSQLdatabase 1.Import tingSQLintoExcel Excelhasanumberoftoolsforimp portingdatafr romexternal sourcesandtheyarevery yeasytouse. locatedontheDataGetExternalData apartofthe ribbon: Theyarel

SQLdatacanbeaccess sedfromFro omOtherSou urces.Thisb bringsupadr ropdownbox xwhereyouc can er.TheFro omSQLServeritembrings supaseriesofwindowst thataskyouf fora selectFromSQLServe me(intheformMachineN Name\Instanc ce)aswellas theauthentic od.Hopefully yyou cationmetho servernam setitupforWindowsa authenticatio onandyoudo onthavetod doanythingelseexceptlea avethedefau ult alone.

ClickingonNext>eitherbringsupa anerror(ifitcannotconne ecttoyourSQ QLServerinst tance)orbrin ngs upawind dowthatallow wsyoutosele ectthedatabaseandthen nthetable.H Hereisthehe elpfulerror messagei ifyoumakea amistake(justclickOKand dtryagain):

Hereiswh hatyougetonsuccess(na ameswilldiffe er)

Thedropd downboxgivesyoutheab bilitytoselect tthedatabas eandthenth hewindowbe elowgivesyo oua choiceoftables.Pickt theoneyouw wantandclick kNext>.Thenextwindow wallowsyout tocreatesom me friendlydescriptivetex xt(optional)b beforeyousa avetheconne ection.Oncetheconnectionfileissave ed youcanre euseit(fromtheData>Ge etExternalDa ata:Existing Connectionstool).Clickf finishtosavethe connectio on.

Onceyouclickfinishitaskswherey youwantyourdataandw hatformat:

Makeany ychangesyou uwantandth henclickOK younowhav veyourdata. Thisdataispermanently loadedint toyoursprea adsheetandis snotlinkedto othedatabas sechangestothesource edatabasewillnot affectyou urcopy. 2.Integra atingSQLinto oyourVBAp programs Theprece edingmethod diseasy,andgenerallythe ewaytogoif youjustneedtoextractd dataonceand dfor allintoan nExcelspread dsheet.Howe ever,therem maybereason nswhyyouwa anttoprogra ammatically interactw withanSQLda atabaseusing gVBA.Howe ever,inorder rtodoso,you uneedtokno owsomething g aboutMic crosoftActive eXDataObjec cts(youwills seethisreferr redtoasADO O).Thisiscom mplicated,bu utif youreuse eexistingcodetodoallthe etediouswor rkofmakingt thedatabase econnection,youcanmak kea fewsmallchangestorunthequerie esyouwant. FromExce el,openupth heVBAeditor randcreatea anewModule etoholdthecode(ifyoualreadyhaveone openforw whateveryou uaredoing,th hatisfine).B Beforeyoudo oanythingels se,youneedt tomakesure eyou havearef ferencetothe eADOlibrary y.Tocreatea areferencecl ickonTools> >Referencestobringupt the windowb below.Locate etheentryfo orMicrosoftActiveXData Objects6.0L Library(orw whateverthemost recentversionnumber ryouhave),c clickthecheckbox,andth enOK.

Ifyoudon ntdothis,yo ouwillgetanerrorwheny youtrytoinst tantiatethen necessaryobje ectstoconne ectto SQLserve er. Thegener ralprocedure eforconnecti ingtoadatab baseisasfollo ows: 1)Figureo outtheconne ectionstringyouwillneed d.Thisisthe HARDESTpa artandyoum mayneedhelp p.If yousetup pSQLservera aswesuggested,youshou uldbeableto ousethefollo owingconnec ctionstring: Const sConnStrin = "Dri s ng iver={SQL Server}; Server= =CALVINATO OR\MSSQL;Database= =beavis;Tr rusted_Co onnection= =True;" Thisisalloneline(thereisalinebreakjustforre eadabilityd dontputthat tin).Thisdef finesaconsta ant uwilluselate erthatidentif fiestheSQLServeronyou rmachinean ndthedatabase.Notethatthe whichyou machinen nameisCALV VINATOR,theSQLServerin nstanceisMS SSQL,andthe edatabaseisbeavis.You shouldreplacethetext tinREDherewiththeapp propriatenam mesforyourinstallationan nddatabase.The restofthe econnectionstringidentif fiesSQLServe erandtheTru usted_Conne ectionparthandles authenticationifyousetittoWindo owsauthentication.Leave etherestalo one. Note:Try yingtodebug connections stringsthatdo ontworkisa anightmarea andnotrecom mmended.Ify you needtom makeanyrealmodification ns(liketoacce essaremote server),gets someoneknow wledgeableto ogive youthere equiredconne ectionstring. 2)Createthenecessar ryvariablesan ndobjectstha atyouwillne eedandopen nthedatabase econnection.You rtheConnec ction,andob bjectforthe Recordsetw whichisthed datareturnedfrom willneedanobjectfor sequery(itiskindoflikeatable).Yous shouldalsoh avevariables sforthequer rystringandi ifyou adatabas aregoingtoputtheda ataintoarang ge,anobjectthatreferenc cesthesprea adsheetrange eyouwantto ouse. syouthefollo owinglinesofcode: Thatgives Define the conn e nection string s

Const sConnString = "Driver={SQL Server}; Server=CALVINATOR\MSSQL;Database=beavis;Trusted_Connection=True;"


Sub dbtest() 'Need to make an object to hold the connection and the results (generic) Dim adoCN As ADODB.Connection Dim rsReturn As New ADODB.Recordset 'Define variables to hold the query and the spreadsheet range (generic) Dim sSQL As String Dim sTarget As Range 'Create connection object and open database (generic) Set adoCN = New ADODB.Connection adoCN.Open sConnString End Sub

Thiscodecanjustbeusedverbatim.Therearelotsofwaystodoexactlythesamethingbutthisworks sononeedtomesswithit.Afteryougetthisfaryoucantryrunningyourmoduleusingthedebugger. Ifthiscoderunswithouterrorthenyouhavethenthehardpartisdone.IfitgivesanerrorlikeCannot CreateUserDefinedObject,youdidntputinthereferencetotheADOlibrary.Mostothererrorswill beduetoabadconnectionstring. 3)Nowyoucandosomethingwithyourconnection.Onethingyoumightwanttodoisextractsome records.Forinstance,IhavetheanordersdatabaseloadedintomyinstanceofSQLserver(thiswas downloadedfromhttp://www.dataminers.com/).Icannowwriteaquerytoreturnallorderswith ordersize>5000andputthelistofordersizesintoanExcelsheetstartingatcolumnA2: This statement is just an SQL query sSQL = "SELECT totalprice FROM orders where totalprice>5000" Run the query and save the result in rsReturn Set rsReturn = adoCN.Execute(sSQL) 'Clears the current sheet ActiveSheet.Cells.ClearContents This creates a range object that you can use to manipulate the sheet Set sTarget = ActiveSheet.Range("A2") Put the result into the spreadsheet range you just defined sTarget.CopyFromRecordset rsReturn

Thissetofstatementsisgenerica)CreateaquerystringthathasyourSQLcomment,b)executeit againstthedatabase,c)dosomethingwiththeresult(inthiscase,copyitintothesheet).Thequery abovedoesntreallydoanythinginteresting(justpullsupadozenorsoordersizenumbers),butifyou candothat,youcandoprettymuchanything. Thereareawholeseriesofadditionalcommandsyoucanusetomanipulaterecordsetobjects,butfor nowIwouldsuggestjustputtingitintoarangesoyoucanusefamiliarspreadsheetcommandsto manipulatetheresults. 4)Thequeryshownaboveisonethatreturnsaresult.Ifyoujustwanttoexecuteaqueryagainstthe databasethataltersthedatabutdoesntreturnaresult,youcanuseslightlydifferentcode. Create your query string sSQL = "INSERT INTO butthead (things, stuff) values('insertedstuff',105)" Execute against the database adoCN.Execute sSQL TheSQLstatementaboveinsertsanewrowintothebuttheaddatabase.Thisdatabasehastwo columns,thingswhichisavarchar(50)andstuffwhichisanint.Notethatsinceyouareinsertinga stringyouneedtodelimitthiswithsinglequotes.Aslongasyouenclosethewholequeryindouble quotesitwillbefineandVBA/SQLwontgetconfused.Theresultisanewrowthathasvalues insertedstuffand105inthetwofields.Notethatforthistowork,youhavetohaveinsertpermission onthedatabase.Onlocaldatabases(onyourownmachine),Idoubtthiswillbeaproblem.However, manyremotedatabases(forobviousreasons)donotallowoperationsotherthanselect. 5)Finallyclosetheconnection.Connections,recordsetsandotherdatabaseobjectscanconsumealot ofcomputerresources,soitisagoodideatodestroytheobjectsonceyouaredonewiththem(you mightalsowanttodothisifthequeryreturnsanerror).Leavingthemopenmayalsocauseunexpected softwarefailures.Thiscodeisoverkillbutillustrateswhatyoucoulddotobethorough: Close the recordset rsReturn.Close Close the connection adoCN.Close Destroy the connection object Set adoCN = Nothing Destroy the recordset object Set rsReturn = Nothing

Thefullcodeforthisexampleisattheendofthisdocumentinaformyoucanjustcutandpaste(just remembertoadjusttheconnectionstringtoyourmachine,andtocreateyourownquery).Thatsit younowhaveallthepowerofSQLandSQLserveratyourcommandthroughExcel. AboutErrorHandling Thecodeabovedoesnotcheckfororrecoverfromerrors.Thisisfineforappletsthatyouwilluseto extractdataforotherprocessingbyhandifyoumakeamistake,youjustgoback,fixitandrunit again.ItisgenerallyNOTokforprogramsthatyouintendtohaveoperateunattendedorapplications youwilldistributetoothers.Errorhandlinginthistypeofscriptarethesameasinanyotherprogram, andwewilladdressthatelsewhere. Appendix:CodeforConnectingtoSQL Youshouldbeabletojustcutandpastethisintoanewmodule.DontforgettosetuptheReferences totheMicrosoftADOlibrary,pickthetypeofqueryyouaredoing,updatethequerystring,and commentoutthecodeforthetypeofqueryyouarenotusingthingsyoumightneedtochangeare markedinRED.
Const sConnString = "Driver={SQL Server};Server=CALVINATOR\MSSQL;Database=beavis;Trusted_Connection=True;" Sub testdb() 'Need to make an object to hold the connection and the results (generic) Dim adoCN As ADODB.Connection Dim rsReturn As New ADODB.Recordset 'Define variables to hold the query and the spreadsheet range(generic) Dim sSQL As String Dim sTarget As Range 'Create connection object and open database (generic) Set adoCN = New ADODB.Connection adoCN.Open sConnString 'Define the query, execute it against the database and store the result 'Change the query string to your own query sSQL = "SELECT totalprice FROM orders where totalprice>5000" Set rsReturn = adoCN.Execute(sSQL) 'Clear a space and then insert database into range starting at A2 ActiveSheet.Cells.ClearContents Set sTarget = ActiveSheet.Range("A2")

sTarget.CopyFromRecordset rsReturn 'Run a query that does not return a result (this one does an insert) sSQL = "INSERT INTO butthead (things, stuff) values('insertedstuff',105)" adoCN.Execute sSQL 'Close out the various objects rsReturn.Close adoCN.Close Set adoCN = Nothing Set rsReturn = Nothing End Sub

Vous aimerez peut-être aussi