0% found this document useful (1 vote)
498 views

Using Excel As Your Database - Chandoo

This document discusses using Excel as a database by treating individual worksheets like database tables and using Visual Basic for Applications (VBA) code and SQL queries to manipulate the data. It provides an example using a customer service dashboard to filter and extract data from an Excel worksheet based on user selections in dropdown menus. The author argues that Excel can be used as a lightweight database solution when database administrators are overworked. The document also includes a link to download an Excel demo file and invites readers to share their experiences using Excel as a database in the comments.

Uploaded by

Albert Aromin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
498 views

Using Excel As Your Database - Chandoo

This document discusses using Excel as a database by treating individual worksheets like database tables and using Visual Basic for Applications (VBA) code and SQL queries to manipulate the data. It provides an example using a customer service dashboard to filter and extract data from an Excel worksheet based on user selections in dropdown menus. The author argues that Excel can be used as a lightweight database solution when database administrators are overworked. The document also includes a link to download an Excel demo file and invites readers to share their experiences using Excel as a database in the comments.

Uploaded by

Albert Aromin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

12/29/2016 UsingExcelAsYourDatabase|Chandoo.

orgLearnMicrosoftExcelOnline

Search

UsingExcelAsYourDatabase
PostedonApril2nd,2012inAutomation,ExcelHowtos,VBAMacros181comments

ThisisaguestpostbyVijay,ourinhouseVBAExpert.

OftenIhavethought,ifIcouldhavewriteSelectEmployeeNameFromSheetWhereEmployeeID=123
andusethisonmyexcelsheet,mylifewouldbesimpler.Sotodaywewilllearnhowtodothis.

PeoplespendalotoftimethinkingwhethertouseExcelastheirdatabaseornot.EventuallytheystartusingAccess
orSQLServeretc.

TodaywewilllearnhowtouseExcelasaDatabaseandhowtouseSQLstatementstogetwhatwe
want.

ExcelasaDatabaseDemo
Wewilllearnhowtobuildthis:

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 1/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline

Beforewebegin:
1.Theentiresheet(wheretherawdatahasbeenstored)willbereferredasonesingledatabasetablebyExcel.
Thisisveryimportanttounderstand.
2.ThishasnothingrelatedwiththeinbuiltTable(2007andgreater)/List(2003andprevious)featureof
Excel.
3.IfyouknowSQL(StructuredQueryLanguage)yourtaskbecomesmucheasier.

SettingupExcelasDatabase
WeneedsomerawdataandwewillutilizeCustomerServiceDashboardsampledatabasehere.

Letsgetstarted.

Firstwewilldesignthestructureofwhatalloptionwewanttopresentforfilteringthedata,whichyoucanseein
theinterfacebelow.

OncetheuserclicksonShowDatawewilluseaSQLstatementtofilteroutthedataasperthedropdownoptions
selectedbytheuserandtheputtheminthetablebelow.

WewillalsouseanotherSQLstatementtopopulatethetoprighthandsidetableforcallsdatawhenallthe3drop
downshavesomeoptionsselected.

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 2/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline

AddingActivexdataobjectsreference
WeneedtoaddareferencetotheMicrosoftActiveXDataObjectsLibrarytobeabletousetheworksheetasa
databasetable.YoucandothisfromVisualBasicEditor>Tools.

Iusuallyselectthemostrecentversion,howeverifyouaredevelopingaproductitwillbebestsuitedifyouare
familiarwiththeoperatingsystemandofficeversionusedbytheenduserssystemandaccordinglyselectthebest
versionavailable.

OpeningExcelasaDatabase
OncethisisdoneweneedtohittheroadwithsomeVBAcode.


PublicSubOpenDB()
Ifcnn.State=adStateOpenThencnn.Close
cnn.ConnectionString="Driver={MicrosoftExcelDriver(*.xls,*.xlsx,*.xlsm,*.xlsb)};DBQ="&_
ActiveWorkbook.Path&Application.PathSeparator&ActiveWorkbook.Name
cnn.Open
EndSub

Theaboveprocedureistheheartofthispost,thisiswherewedefinehowtousethecurrentExcelworkbookasour
database.

cnn.ConnectionString="Driver={MicrosoftExcelDriver(*.xls,*.xlsx,*.xlsm,*.xlsb)};DBQ="&_
ActiveWorkbook.Path&Application.PathSeparator&ActiveWorkbook.Name

Onthisline,wedefineallthepossiblefileextensionsthatweareallowedtocreateanExcelWorkbookandthenuse
asourdatabase.

Letsunderstandthecodemodule
WhenyouclickontheUpdateDropDownsbutton,theVBAcodeusestheDataworksheetasatableandthen
findsuniquevaluesforProducts,RegionandCustomerTypesandthenpopulatesthemasListItemsforthe
ComboBoxcontrols.

ExampleforProductsdropdown


strSQL="SelectDistinct[Product]From[data$]Orderby[Product]"
closeRS
OpenDB
cmbProducts.Clear
http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 3/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF

cmbProducts.AddItemrs.Fields(0)
rs.MoveNext
Loop
Else

MsgBox"IwasnotabletofindanyuniqueProducts.",vbCritical+vbOKOnly
ExitSub
EndIf

WhatisimportanttonoticehereishowtheTableandFieldshavebeenidentifiedusingsquarebracketsunlike
traditionalSQLwherewejustprovidethename,alsothetablenamehastobesuffixedwitha$symbolattheend.

AsIhavesuggestedearlier,oneentiresheetwillbetreatedasonesingletable,soifyouhavemultipledatasetsthat
werecurrentlyorganizedwithinonesheetyoumayhavetocreatemultiplesheetstostorethatdatatobeableto
usethemastables.Thiswouldalsomakemaintenanceofdataeasier.

UsingExcelSQLtoconsolidatetwosheetsintoone
Manypeopleask,howtoconsolidate2ormoresheetswhichhavethesimilardata.WellIwouldhave
adoptedthismethodandwroteasimplequeryasbelow.


SELECTID,FirstName,MiddleName,LastName,Age,DOBFrom[Table1$]
UNIONALL
SELECTID,FirstName,MiddleName,LastName,Age,DOBFrom[Table2$]

Thiswouldallowmetouseboththesheetsasonetableandfetchallofmydataintoanewsheet.

DownloadExcelAsDatabaseDemoFile
Clickheretodownloadthedemofile&useittounderstandthistechnique.

DoyouuseExcelasadatabase?
DoyoualsouserExcelasyourdatabase?Ifyespleaseputinthecommentbelowhowdoyouusethesame
andwhathasbeenyourexperience.Leaveacomment.

MoreonVBA&Macros
IfyouarenewtoVBA,Excelmacros,gothrutheselinkstolearnmore.

WhatisVBA&Macros?Introduction
ExcelVBAExampleMacros
VBAtutorialvideos

JoinourVBAClasses
Ifyouwanttolearnhowtodevelopapplicationsliketheseandmore,pleaseconsiderjoiningourVBAClasses.Itisa
stepbystepprogramdesignedtoteachyouallconceptsofVBAsothatyoucanautomate&simplifyyourwork.

ClickheretolearnmoreaboutVBAClasses&joinus.

AboutVijay
Vijay(manyofyouknowhimfromVBAClasses),joinedchandoo.orgfulltimethisFebruary.Hewillbewritingmore
oftenonusingVBA,dataanalysisonourblog.Also,Vijaywillbehelpinguswithconsulting&trainingprograms.You
[email protected],saythankstoVijay.

Sharethistipwithyourfriends

Facebook LinkedIn Twitter Google Email Print

181ResponsestoUsingExcelAsYourDatabase

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 4/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline

1. Grahamsays:
April2,2012at10:26am

Worstthingevertodo.ExcelisasmuchadbasisAccess.

Useexcelasaspreadsheetandleavedatabasesworktodatabases.

It'sbadenoughseeingspreadsheetswithmultipleworksheetsbeingusedandscrewedupbypeoplewithout
lettingthemthinkit'sadatabase.

Excelhasaplaceinbusinessjustnotasadb.

Reply

Ivosays:
April2,2012at5:40pm

InmanycompaniesDBpeopleareusuallyoverworkedandeveryoneelseisjuststuckwithlargeExcel
datafilesthatneedtobemanipulated.Insuchcasesit'sunreasonabletoexpectpeopletowaituntil
theDBpersongetstotheirissuesomanagingthedatainExcelisagoodoption.

Reply

Jeff"DrSynthetic"Wilsonsays:
January1,2013at6:24am

Worstthingevertodo.ExcelisasmuchadbasisAccess.
Useexcelasaspreadsheetandleavedatabasesworktodatabases.
Itsbadenoughseeingspreadsheetswithmultipleworksheetsbeingusedandscrewedupbypeople
withoutlettingthemthinkitsadatabase.
Excelhasaplaceinbusinessjustnotasadb.>>>

ImighthaveagreedwithyouthruExcel2007butsincetheadventofPowerPivot,Excelisasmucha
databaseasanyotherrelationaldatabase.IsuggestyoureadeitherRobCollie'sbook"DAXFormulas
forPowerPivotorBillJelen'sPowerPivotfortheDATAAnalyst"(emphasismine)Thisisa
gamechanger

Reply

arunsays:
September25,2013at10:31am

Hi..ineedtodoasmallprojectwithtwotextboxeshereineedtoretriveandinsertthedatain
database.herethedatabaseineedtouseisMicrosoftexcel2007......canuexplainmeitby
stepbystepprocedure

Reply

GaroudaHanoumansays:
April17,2013at4:46am

Idon'tlikenegativecommentslikethatone,Imustsay!
Ifyoulikeargueaboutthesexofangels,IwouldsaythatAccessisnotabulletproofdatabaseeither...
Thisisagreattutorialandithelpsmealot.IhavetwotablesinAccess,onewiththeprovinces,
districtsandpostalcodesinThailand.Iaddedthesecondonewiththetambon(subdistricts).Thefirst
hasgot928records,thesecond7373records.Iwanttokeeponlyonetablebywritingthepostal
codesinthesecondtable.Thisisaoneshotaction,sowhyshouldImodifymyVB6/ADODB/SQL/MsJet
programmeforthatpurpose???IamgladtouseSQLinsteadofa'Find'inVBA.
ThanksalotChandoo

Reply

wXronXgsays:
August23,2013at7:53pm

ItotallydisagreewithyoubecauseI'vebeenusingExcelasadatabaseforseveralyearsalready.
Accessmightbesuperiorinhandlingandstoringdata,but,asinmycasewheremydataareupdated
almostdaily,andIneedinstantanalyses(whicharecomplexIshouldsay)tomonitorprogress,Excel
isthebestwaytogo.ChartsarealsoeasiertocreateandupdateinExcel(myAccesscan'tevencreate

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 5/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
achartunlessyoucopypasteitasanimage!).Ithinkitdependsontheneedorcircumstancesand
nobodycouldconcludethatacertainprogramshouldnotbeusedforacertaintaskevenifithasthe
capability.Also,thisisanExcelandnotanAccesssite...

Anyways,itisgoodtoknowthatSQLcouldbeusedinExcel.IshouldreallylearnhowtodoitASAP!
Asofnow,I'musingtheFor...Nextlooptosearchforaparticulardatainmymacroswhichseem
"UNawesome"!

Reply

2. kafransays:
April2,2012at1:07pm

HeyChandooisthistaughtatExcelSchool?Man,thisistheawesomenessthingIhadeverseen!

Reply

Chandoosays:
April3,2012at2:03am

@Kafran...ThisisincludedinourVBAclass.Visithttp://chandoo.org/wp/vbaclasses/ifyouwouldlike
tojoinus.

Reply

3. Ashwinsays:
April2,2012at2:18pm

ExcellentandthanksVijayforprovidingsuchasaneasywaytocreateDBusingEXcel.

Ashwin

Reply

4. Pankajsays:
April2,2012at5:06pm

Excelhasdatabasefunctions.http://office.microsoft.com/enus/excelhelp/CH006252820.aspx

Ifyouusethis,youcanavoidVBA.Iusetheseforworkandvisualizationpurposes.Asamplefilecanbe
downloadedherehttp://pankaj.dishapankaj.com/share

Reply

5. DaveGsays:
April2,2012at5:06pm

Fantastic.
IuseExcelasa'database'butusingmoreconventional(nonvba)methodssothisisgreat.

IagreewithGraham,insofarasExcelisnotdesignedtobeadatabaseandthereforeyoushouldkeepitsuse
toaminimumandmakeexceldowhatitsbestat,numberanddatamanipulation,notdatarelationship
management.However,onoccasionitisveryhandytouseitinaminorwayasadatabaseinsteadofhaving
tolinkdifferentapplications(whichsometimesisnotpossibleduetoITsecuritypolicies)toachievearesult.

Morearticleslikethisareamust.
Thanks
Dave

Reply

6. Manicksays:
April2,2012at6:20pm

Great!Whatacoincidence?Onlyyesterday,Iwassearchingfor"database"inthissite&didnotgetmuch
information.

WhileIagreethatAccessisbetterusedasadatabase,therearesituationswhereweareforcedtouseExcel.
Pleasewritesomemorearticlesondatabases.ThanksVijay!

Reply

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 6/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline

7. mustafasays:
April2,2012at6:28pm

ThankyouverymuchVijaythisisreallycreativework.Ihopeitwillcontinue.

Ihavelikedyourteachingonvbaclasstoo.thanksagain.

Reply

8. Gerardsays:
April2,2012at7:37pm

IagreeaboutthefactthatExcelisn'tadatabasebutIthinkit'sgreat.Seepracticaluseinaselectnumbers
ofsituations.UseitwiseIwouldliketosay.ThanksfortheinformationandIlookingforwardonmoretopics.

Regards
Gerard

Reply

KHADIMHUSENsays:
June5,2016at1:58pm

Ihaveseenexcelfile.

Itseemitinnothingotherthanfilter.

Reply

9. JeffWeirsays:
April3,2012at4:07am

Goodlittledemo.Notethatthesquarebracketsareonlyneededifyourtableorcolumnnamehasaspacein
it.ButIthinkitsgoodpracticetousethemwhetherornotyourtableorcolumnnamehasaspaceinit.

Youcanalsousethischaractertodothesame:`

Forinstance,youcouldremovethebracketsfrom[data$]withandthequerystillworksfine.Butyoucould
notremovethebracketsfrom[CustomerType]becauseofthespace,althoughyoucoulduse`Customer
Type`inplaceof[CustomerType].

InregardsofwhetheryoushoulduseExcelasadatabase,Idon'tseewhynot.What'sworthpointingoutis
thatyoucanalsomodifythisapproachtotakedatafromjustaboutanydatabaseandpresentitinExcel.

I'dbeinclinedtonothardcodethesheetnameintothiscode.Insteadi'daddthistobothmodules:

DimsSheetNameAsString
sSheetName="["&Sheet2.Name&"$]"

...andthenreplaceall11instancesofthis:
[Data$]
...withthis:
"&sSheetName&"
(includingthequotemarks)

Reply

10. Udaysays:
April3,2012at8:34am

IhavebeenusingEXCELasafrontendformanagingdatainAccessDB.Butcouldnotfindanyeasywayto
managethemovementbetweenrecordsandotherfeaturesthatwereavailablewithVB6"DataControl".

IsthereanythingequivalentavailableinEXCEL2010?

Regards,

Reply

VijaySharmasays:

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 7/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
April3,2012at9:54am

@Uday,

TheVB6DataControlwasbuiltforsuchtasksandfunctionality.Howeverthereisnothingnative
withinExceltosupportthis.

Couldyouspecifiywhatexactlyyouareafterandmaybewecancreatesomethingthatwouldbenefit
everyone.

Reply

Udaysays:
April3,2012at10:20am

ThanksfortheresponseVijay.IhavebuiltautilityinEXCEL/Accessformaintainingmy
Expense/IncomeaswellasInvestmentsinaconsolidatedformthatalwaysgivesmeuptodate
reports.

ThedataisobviouslyinAccessandsoisthe"Master/TransactionMaintenance".WhatIhave
doneisbuiltthemaintenancefunctionusingEXCELVBA/Formsbutyouendupwritingahuge
codeforallfunctionsexplicitly(add/modify/delete/view).
Wantedtoknowifthereisanythingavailablethatcanreducethisdevelopmenttime?

Cheers,

Reply

JeffWeirsays:
April4,2012at3:02am

HiUday.Averycleverguyi'vegottoknowcalledCraigHatmakerhaswrittenagreat
ExcelApptoupdateanexternaldatabase.It'sstillaworkinprogress,butit'sveryvery
clever,andtherearesomeverygoodfunctionstoallowyoutomodifythedatabasethat
youcouldprobablyamend.

ToquotefromCraig'sowndocumentation:
TherearetimeswhenExcelisperfectformanipulatingdataindatabases.Examples
includetariff/ratetables,journalentries,andemployeetimesheets.Excelalsoworkswell
formaintainingsimplelistslikecodefiles.

TraditionalapproachestoleveragingExcelindataentryhaveenduserskeydataintoa
formattedspreadsheet,saveittoashareddirectory,thenrunaserversideprogramto
checkdata,andifeverythingisokay,updatethedatabase.Thisapproachhasmultiple
objectsondifferentplatformsinvolvedinasingletaskcomplicatingdevelopmentand
maintenance.Inaddition,validationresultsaredeliveredwellafterentrieshavebeen
madefrustratingendusers.

Abetterapproach,inmyopinion,istoputthatsamevalidationandupdatelogicfromthe
serverprogramintotheExcelentrysheetsotheresjustoneobjecttomaintain.Thishas
theadditionalbenefitofprovidingenduserswithimmediatefeedbackastothevalidityof
entries.

ThoughthisAppspecificallyupdatestheEmployee2003tableinMicrosoftAccessdemo
database,Northwind2003.accdb,thetemplatecanbeeasilymodifiedforusewithany
database.

Craigtellsmehe'shappyformetosharethefilewithyou.Flickmealineat
[email protected]'llsendyoualinktothedocumentationaswellastheaccess
tableandexcelappheuses.

Also,checkoutCraig'sblogat

http://itknowledgeexchange.techtarget.com/beyondexcel/forward/

Reply

11. NARAYANsays:
April3,2012at9:45am

HiVijay,

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 8/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Thanks.

Narayan

Reply

12. AnalysisParalysissays:
April3,2012at1:14pm

Iagreewithmostofthecomments.NeveruseExcelasaDB.

UseAccessoranotherDBtohandleallyourdatathenjustsetupanodbcanduseExceltomakeprettythe
data.

Reply

13. ADITYAsays:
April3,2012at1:24pm

hi,
ihaceado2.6.iusewindowsxpandoffice2007.
howcanifindversion6.0.
regards
Aditya

Reply

VijaySharmasays:
April4,2012at2:42am

@Aditya,

Version6.0isavailablefromWindowsVistaonwards.

ThebelowlinktalksabouttheversionhistoryforMDAC.
http://support.microsoft.com/kb/231943
(howeverthereisnomentionof6.0).

AnotherhelpfulatricleIfoundwas...
http://www.vbforums.com/showthread.php?t=527673

Reply

Fahmisays:
December26,2012at3:41am

hivijay,whywhenichangethecomboboxtocallthedatabydate,it'salwayssay"datatype
mismatchincriteriaexpression".canyouhelpmetosolvethisproblem?
ithinkitsbecausethedateformat,maybe

Reply

14. Susansays:
April3,2012at4:53pm

Vijay
ThankyouforgivingthoseofuswithoutacopyofAccesstheopportunitytokeepprogressingwithExcel.
Verygoodinformation!
Best
Susan

Reply

15. Devnathsays:
April3,2012at6:49pm

Thanks,Vijayforpostingonthetopicuseexcelasdatabase.Ihopethishashelpedmanyofexcelusers.

Reply

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 9/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline

16. DaveThorntonsays:
April4,2012at4:14pm

HiChandoo,

Iunderstanddescribingthistechniqueas"usingExcelasyourdatabase",foralackofabetterterm.Butit
couldbemisleading.Excelmakesforapoordatabase,butyourarticleisnotreallybastardisingExcelinlieuof
aproperdatabaseassomemayinterpret.ThemainconceptsinyourarticleareaboutusingADOandthe
ExcelODBCdriver.Thistechniqueapplieswhetheryou'reusingatextfile,SQLServertables,orspreadsheets.
Therefore,IlookatitmorelikeusingExcelasyour"datasource".Ithinkitwouldbevaluableifyoucould
explainthatalittlemoresothatpeopleunderstandthecontext.Thisisapowerfulandtimesaving
technique,greatforanyone'sarsenal,soit'ssadtoseepeoplemakeblanketstatementsagainstit.Although
Idoagreeinprinciplethatdatabasesmakebettersourcesthemajorityofthetime,therearevalidreasons
forusingADOandExcelinthisfashion.

Inaddition,Ihopepeopleunderstandthatyoucanalsousequerytablesandlistobjectstoaccomplishthe
same.TheaddedbenefitisthatyoucanrecordmacrostogetgenericVBAcode,don'thavetoworryabout
references,andcanalsouseMSQuerytofinetuneyourSQLifyou'renotfluent.

Lastly,peopleshouldunderstandthattherearesignificantcaveatslikehowdatatypesaredeterminedor
issueswithcomplexSQLstatements.Icangetintomyexperienceswiththisifanyonewantsmoredetails.

Reply

17. Paleksays:
April4,2012at7:56pm

Thisisgreat.WhenIdownloadtheExceldatabasedemoIkeepgettingerror.Isthedemonotworkingfor
otherstoo?

Thanks

Reply

18. Davesays:
April5,2012at6:00am

Itworkedforme.Ifirstdownloadeditusing"open"insteadof"save"andIgoterrors.Ilookedatthecode
andtheadoconnectionwasreferencingthespreadsheetfromhttp://img.chandoo.org/vba...ratherthanmy
computer.Ithensavedthefiletomydesktopandranitfromtherewithnoproblems.

Reply

debsays:
September17,2015at8:11am

canyouexplainhowtochangethecode....i'mgettingthesameerrors

Reply

19. JosLbosays:
April9,2012at6:24pm

Hi,Ijustwanttoaddthoselinesforuseinthecaseyourdatabasehasoneormorefield'sdate(column),and
youneedtoselectdatafromainterval.
IthinkthisisusefulbecauseSQLhasmanysintaxe'svariationandthisworkswithVBA:

dvenc1=Format(Sheets("View").Range("G6").Value,"dd/mm/yyyy")
dvenc2=Format(Sheets("View").Range("H6").Value,"dd/mm/yyyy")
dpago1=Format(Sheets("View").Range("G7").Value,"dd/mm/yyyy")
dpago2=Format(Sheets("View").Range("H7").Value,"dd/mm/yyyy")

strSQL="SELECT*FROM[data$]WHERE([vencimento]"&_
"between#"&dvenc1&"#And#"&dvenc2&"#)"

strSQL="SELECT*FROM[data$]WHERE([pagamento]"&_
"between#"&dpago1&"#And#"&dpago2&"#)"

Reply

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 10/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline

Mohammadhassanisays:
June8,2013at2:21pm

dearJosLbo

verythanksforyouroperationalcods

Reply

20. Jaysays:
April12,2012at5:32pm

Hey,Ilikethis.Thisalsohasapracticalsidewherethedatawill"eventually"endupinatrueDB.

However,Ihaveaquestion:Idownloadedthesamplefile,andwasunabletorunitbecausetheadolibrary
wasn'tactivated.

Ifthisfilewassharedwithothers,wouldtheyalsohavetoenablethecomponentinexcel?Isthereawayto
makethishappenautomagically(tm)?

Thanks

Reply

21. JosLbosays:
April13,2012at12:44am

Jay,Ifoundthecodebelow,thatcanautomaticload/unloadthelibrary,ifithasbeeninstalledinyour
machine:

'Putinthemodule"Thisworkbook"

PrivateSubWorkbook_Open()
MsgBox"Oi,obrigadoporcarregaraBiblioteca",vbInformation,"JFLbo"
'IncludeReferenceLibrary
'MicrosoftActiveXDataObjects2.8Library
OnErrorResumeNext
ThisWorkbook.VBProject.References.AddFromFile"C:\ProgramFiles\CommonFiles\System\ADO\msado15.dll"
EndSub

PrivateSubWorkbook_BeforeClose(CancelAsBoolean)

'removeADOreference
DimxAsObject
n=Application.VBE.ActiveVBProject.References.Count

DoWhileApplication.VBE.ActiveVBProject.References.Count>0Andn>0
OnErrorResumeNext
Setx=Application.VBE.ActiveVBProject.References.Item(n)
y=x.Name
Ify="ADODB"Then
Application.VBE.ActiveVBProject.References.Removex
EndIf
n=n1
Loop

EndSub

Reply

22. Jaysays:
April13,2012at2:29pm

awesome,thanks.

IalsofoundthatIcanenableallthe"ADO"librariesbacktosomepoint,say2.6,andordertheir"priority"
andsavethedocument.Theywillshowas"missing"ifyoulookinyourreferences,howeverthecodewillstill
run.Seemstheoriginalattemptedtoload6.0,whichIdidn'thave.Now,withtheothersspecified,it
eventuallyfoundonethatworked.inotherwords,thereferencewasactuallysavedwiththefileand
automaticallyloaded,Ijustdidn'thaveit.

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 11/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Reply

23. MickCsays:
April18,2012at1:03pm

I'veneverseenabetterwaytouseExcelasadatabasethanviaLaurentLongre'sIndirect.extfunction.Set
upmultipleExcelspreadsheets,populatethedata,thenconsolidatethemwithoutopeningthemI'veusedit
manytimesandit'sfoolproof...noneedforVBA,justusingyourbrainforthedataanalysispieceafterwards.

Reply

24. Danielsays:
April20,2012at3:12pm

ItriedtomodifythequerytoSelectbasedon[DateTime]andencounteredthefollowingerrorwhenclickon
ShowData
[Microsoft][ODBCExcelDriver]Datatypemismatchincriteriaexpression.

ThiscouldbeduetorestrictionwherethevaluehastobeatextvalueinsteadofDateValue.

Anysuggestionhowtoovercomethis?

ManythankstoVijayforthisfantasticpost

Reply

25. JosLbosays:
April20,2012at4:23pm

Onapostabove,dated(04/09),Igaveanexampleofselectingdatesintoaninterval.Datesareontheirright
formatonthecell.

Reply

26. Ankitasays:
April24,2012at1:27pm

HIVijay,

Thankforpostingthisthread.Iusedtheexcelsheetandammendeditaccordingtomydata.Nowthe
problemIamfacingisthatwhenIruntheUpdatedropdownbuttonIamgettingerror[MICROSOFT][ODBC
Exceldriver]Toofewparameters.Expected1intheliners.OpenstrSQL,cnn,adOpenKeyset,
adLockOptimistic.canupleasehelpmeoutonthis.

Reply

VijaySharmasays:
April24,2012at1:34pm

HelloAnkita,

YourSQLstatementneedstobelookedat.Youmaysendmethefileatsharma.vijay1@gmail.comto
lookat.

~VijaySharma

Reply

Ankitasays:
April24,2012at2:04pm

Ihavemailedyouthefile.Pleasetakealook.Thanks

Reply

Jimsays:
April24,2012at5:54pm

Ireallyamintriguedbythisarticle,howeverIkeepcrashingtheprogramwhenIsaveit.Itried
thesolutionfromJoseandamstillgettingthesameerrors.Theerrorsarebelow:

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 12/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Yourchangescouldnotbesavedto'Excel_AsDatabasedemov1.xlsm"becauseofasharing
violation.Trysavingtoadifferentfile.

WhenItrytosaveittoanotherfile,Igetthemessage:"Thefileyouaretryingtoopen,
'791CF000',isinadifferentformatthanspecifiedbythefileextension.Verifythatthefileisnot
corruptedandisfromatrustedsourcebeforeopeningthefile.Doyouwanttoopenthefile
now?"

Isaveditasanewworkbookandthesameerrorsappear.

Anythoughtswouldbegreatlyappreciated.

Thanksinadvanceforyourhelp

Reply

Jurgensays:
August29,2012at8:33pm

HelloJimandVijay,

Ihavethesameproblem.Ihavedownloadedthedemofile.Whenichangesomethingin
thedatasheetandjustclickontheupdatedropdownbutton.It'snotpossibletosavethe
fileanymore.

ItsgivemethesameerrorYourchangescouldnotbesavedtoExcel_AsDatabase
demov1.xlsmbecauseofasharingviolation.Trysavingtoadifferentfile.

Istherealreadyasollutionforthisproblem.

Reply

MYudhaTristiantosays:
September26,2014at9:20am

trythis
cnn.ConnectionString="Driver={MicrosoftExcelDriver(*.xls,*.xlsx,*.xlsm,
*.xlsb)}DBQ="&_
ActiveWorkbook.Path&Application.PathSeparator&ActiveWorkbook.Name&
"ReadOnly=false"

ConradoNatacsays:
November6,2014at6:06am

HiVijay,

Iwaswonderingifyoucanhelpme.Itriedtouseavariableonmysqlstatementanditkeeps
gettinganerror.

Canyouhelpfigureouttheproblem.

DimxtypeAsString

'thisistheinvoicetype
xtype="I"

closeRS
OpenDB

strSQL="SELECT*FROM[data$]WHERE[data$].[Type]="&xtype_
&"and[data$].[Cust#]='"&cmbcustno.Text&"'"

closeRS

'thisistheconnrection
OpenDB

'thisistheerror

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic

Thanksalot.

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 13/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Conrad

Reply

27. Chrissays:
May29,2012at2:10am

Technicallythisprovidesdatabaselikequeryfacilities.It'snotprovidingdatabasecapabilityinexcel,asa
spreadsheetisincapableofbeingadatabase.Aspreadsheethasnoconcept(orabilitytorepresent)tuples
andrelationshipsbetweendatawithprimaryindexes.Butthenmostpeopleatworkdon'tseeanydifference
atall,andcallaspreadsheetadatabaseandviceversa...happilyintroducingdataanomaliesalongtheway.It
hasbeenestimatedthat95%ofspreadsheetsinworkplacescontainerrors...sotreatingaspreadsheetasa
databaseisjustonemoreproblemoftechnologyinhandsofthelittetrained.
Imustsayi'veseensomedoozyformulasandspreadsheets,boththeWTFkindandthekindwherean
inordinateamountoftimeandmoneywasspenttocreateaspreadsheet,wheresomethingelsewouldbe
muchbetterandwaymoreefficient.spreadsheetsarenotscriptinglanguagesandherendousformulasget
createdwhenscriptinglanguageshouldbeusedinstead.butnevermind.
keepupthegoodworkpeople,teachingthegoodstuff.

Reply

Jaysays:
June13,2012at3:53pm

Agreed,

However,youareassumingthat,whenaDBisneeded,oneisactuallyavailabletotheuser.Many
timesthisisnotthecase,andthedataforthespreadsheetisactuallyrequiredtobecontainedinthe
spreadsheetitself.Ihappentobeinthisboat.Iwouldmuchratherusepropertoolsforthejob,they
justaren'tavailable.Thisismuchbetterthanjust"well,can'tbedone."Evenmoreso,thisismore
likeusingaBallPeenhammerwhenwhatyoureallyneedisaframinghammer.Ratherthansay,
usingapipewrench.Atleastis'tinthesamefamily.Itwon'tbeaseffective,butit'snotacomplete
hack(likemanyoftheexamplesyoucite)

Reply

28. Richardsays:
June13,2012at11:54am

ExceltoDatabasenowsupportsMySQLaswellasSQLServerandAccess.
ThetoolallowsyoutoprevalidatedataandquicklyuploadfromExceltodatabaseandevensenddatatoa
storedprocedure!
Wellworthalook!
http://leansoftware.net/Forum/default.aspx?g=topics&f=4

Reply

29. JeffWeirsays:
June13,2012at10:07pm

People...checkoutMicrosoft'saddinforExcelcalled"PowerPivot".

PowerPivotforExcelisanaddintoExcel2010thatprovidesthefoundationtoimportandcombinesource
datafromanylocationformassivedataanalysisonthedesktop,includingrelationaldatabases,
multidimensionalsources,cloudservices,datafeeds,Excelfiles,textfiles,anddatafromtheWeb.

Thedatathatyouaddtotheworkbookisstoredinternally,asanembeddedPowerPivotdatabaseinsidethe
.xlsxfile.



Fromauserperspective,keypointsare:

Itallowsdatapeopletoquicklycreatemashupsofdisparatedatasourceontheflyincludingwebdata,text
files,datawarehousefiles,andexceltablesandserveitupasapivottable.
ItextendsthecapabilityofExcel2010sothatuserscancrunch,filter,sortmillionsofrecordswithverylow
overhead,aswellasincorporatebothrelationalandnonrelationaldatasourceseasilyintoanalysis,usingan
interfacetheyarealreadyfamiliarwith.

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 14/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline



ItcanbeprogrammedwithSQLorDAX,butusersdontneedtowriteSQLorDAXqueriesinordertouseit
(althoughtheycaniftheywant).Behindthescenes,PowerpivotcreatesOLAPcubes,anddrawsheavilyon
componentsofSQLServertodothis,butnoistallofSQLServerisrequired.



ThisaddinextendsthecapabilityofExcelsomuchthatitmightwellremovetheorganisationalneedforsome
oftheotherappsinsomecases(suchasSAS)andmaketheirlicencingcostsdisappear.



GivenExcelwouldbemostorganisation'smostwidelyused/deployedtool,andthatthisfreeaddinisthe
mostsignificantadvancementinExcelinthelastdecade,Ithinkthiswouldraisethebaronwhatyour
averageanalystcoulddo,andlowerthetotalcostofdoingit.
Furtherbenefitsoftheaddinlistedathttp://msdn.microsoft.com/enus/library/ee210644.aspx

Reply

Jaysays:
June29,2012at1:53pm

Yes,I'vebeeneyeingthePPpluginforsometimenow.Ourcorpwon'tbemigratingusersto2010for
sometimethough....sigh.Atleastitgetsustimetoreqansqlserverthough.basicallythistechnique
willallowmetogetmuchofthedevworkframedbeforethesqlservergoesup,theneventually
replaceitwiththeppplugin.

Reply

30. umeshsays:
June29,2012at8:04am

Mycomputerdoesn'thaveMicrosoftActivexDataovjects6.0Librarysohowtogetthis

Reply

VijaySharmasays:
June29,2012at9:51am

HelloUmesh,

Whatistheoperatingsysteminstalledonyoursystem.ThisversionisavailablefromWindowsVista
onwards.

VijaySharma

Reply

31. Jaysays:
June29,2012at1:56pm

Now,ifIcouldjustgetanexampleof"filtering"data,withoutusingapivottable,thatsupportsmultiselect
filters.Vijay?gotaslicksolution?rightnowIamcopyingfiltersettingsviavbatomultiplepivottable,and
it'scrap,slow,andmorecrap.Ididsomethingwithsomenamedrangesandcheckedboxes...itwasokish

Reply

32. JeffWeirsays:
June29,2012at10:01pm

Jaycanyouelaborateabitmoreaboutwhatyouaretryingtodo?I'mdevelopinganaddinsothatusers
canveryeasilyfilteranyexistingpivottableQUICKLYbasedonanamedrangei.e."FilterpivottableAbased
onalltheentriesinrangeB".I'mdoingthisbecausei'venoticedthatusersspendsignificantamountsoftime
manualyfilteringpivottablessothattheymatchitemsinanotherdataset.

Oneproblemwithfilteringpivottablesistheremightbetensofthousandsofpivotitemsinanyonefield,so
iteratingthroughthemcantakesignificanttime.Thatsaid,I'vefoundaverysmartwaytoiteratethrough
them,plusamdevelopinganotherapproachwhereIdon'thavetoiteratethroughthecollectionatall.

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 15/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
However,forpivotfieldswithtensofthousandsofitems,filteringthemwithSQLwillalwaysbequicker.

Reply

Hui...says:
June30,2012at2:44am

@Jay

InadditiontoJeff'scommentsIoftenwilldoaprefilterfirstusinganAdvancedFiltertogetridofthe
bulkofnonimportantdata

ThenrunthePivottableonthefiltereddata

Reply

33. Jaysays:
July3,2012at3:54pm

yes,theproblemis:Ihavealargesetdatasets(saythatfastfivetimes!)withabout8commonfields.The
powersthatbewanttobeabletofilteronabout6ofthoseatanygiventime.MOSTofthefiltersare
restrictedtoaboutadozenorso,howeverthereareafewthatnumbercloserto100.andofcourse,they
want:Abilitytomultiselect,allpivotfilterslinkedtoamasterfilter.I'veusedavarietyofvbandother
techniquestolinkthefilters,butofcoursecopyingthose100ishitemsto610otherpivottablesultimatelyis
timeconsuming.I'dmuchratherusethissqltechnique,butIdon'tknowhowtosupportthemultiselect.I
havedoneitinthepastbyusingthepivot_changeevent,dupingallthefiltersettingstoatable,thenusinga
formulainthedataforeachtabletoset"inscope".thatfiltersettingispresetto"true"forallpivots,and
hidden.itsbetter,butnotgood.Themostefficientihavedoneistoputthedataforeachofthe"100ish"
intoseparatetabs,usesumifsonthemainpage,andmove"outofscope"tabsoutsidethesumiftabrange,
againakludge(butsurprisinglythefastestmethod)IthinkIcouldapplythismethodusingatreeview
controlastheinput(s)ratherthanaselectbox...Inreality,weshouldn'tbeusingexcelasourpresentation
layer,butalas,weare!

Reply

34. JeffWeirsays:
July13,2012at6:59am

@Jaytheywant[the]abilitytomultiselect,allpivotfilterslinkedtoamasterfilter.IftheyhaveExcel2010,
thenslicersareadamneasywaytodothisassumingallpivotsrunoffthesamecache.(Thatsaid,there'sa
wayaroundthatthatIwanttotryout).Otherwise,Debrahassomecodeat
http://blog.contextures.com/archives/2012/01/03/changeallpivottableswithoneselection/thatmayhelp
(althoughitmighttakesignificanttimetoiteratethrougheachpivottableandeachpivotfield,andeach
pivotitem)

IdontknowhowtosupportthemultiselectSound'slikeasimpleWHEREINclausewoulddothetrick.
Canyoupostasamplespreadsheetsomewhereformetohavealookat?

Reply

Jaysays:
July13,2012at2:47pm

Yes,I'dloveforthemtomoveto2010,thenI'dgowiththePowerPivotpluginandmovethedatato
ansqlserverthatweshouldbegettingsoonish.Ihaveusedthecodeyoulinked,oravariant.It's
slow,butworks.Iactuallyuseadifferent"hack"Ihavefoundalittlefasterforlargefiltersets,butit's
notpretty.Ihavebeenlookingatthismethod.Ilikeit,since2ofthelargefiltersareinterdependant
(dependingonwhatisseton1,Icanreducethesecondfilterchoicessignificantly)Ijustneedto
figureoutanelegantwaytodomultiselect.IthinkIhave.Ican,intheoryuseaTreeViewcontrol.
TheListBoxcontrolwithmulitselectalsomightworkwell,particularlyforthe"noninterdependent"
filters.ThenbuilduptheSQL,probablywithan"Apply"button.I'llletyouknowifIgetittowork
well.

Reply

35. vinothsays:
July25,2012at6:44pm

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 16/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
HI,
Iamanoviceonexcelvba,iusedtocompletethetaskwhateverassignedtomebysearchinggoogle,on
searchingifoundthislinkanditisveryveryuseful.Thequerywhichigotwasintheattachmentattachedin
thisposttheproductfieldgotsomeproductrelatedinformationbutifiputDateinitsplaceitdidn'tfiltered
out!!.canyoupleaseadvicehowcanitbeachieved??andalsoadviceushowcanweproceedtheabove
functionwithonlyonekeysaydatefieldalone(inthistutorialuused3keys).

Reply

36. Bee_Boosays:
August6,2012at10:54am

Hi,
iamcompletelyuntouchedbyprogramming(ifyoudontcountinsomeclassesmanyyearsago),andmygoal
istocreatestockdatabase.Forfilteringofwhatihaveinstock(andmovements)icanuseyourstutorialto
filteroutdataineedtosee,butwhataboutaddingnewrowstodatasheet?Itispossibletodoitinsome
kindofdialoguebox?
Thanksforhelp.

Reply

37. Richardsays:
August6,2012at11:42am

@Bee_Boo,perhapsyoucouldtakeadvantageofExceltodatabasetoinsertnewrows?
http://leansoftware.net/enus/productsdownloads/exceltodatabase.aspx

Reply

38. Vrundasays:
August27,2012at12:25pm

VijaySir

Likejimsaidon24042012IamalsogettingsameerrorsrepeatedlywithsomeAlphanumericName
generatedexcelfile...Isthisduetousingexcelasdatabase??
2)Willthedatabelostifweusethiscode&willtherebeanyproblemtoourcomputerforsame....
Whythistypeoferrorsarecoming??PleaseClarify

Reply

VijaySharmasays:
August28,2012at12:38pm

HelloVrunda,

Kindlyshareyourworkbookwithmeatsharma.vijay1@gmail.comtolookatandfigureoutwhatis
goingwrong.

~VijaySharma

Reply

Jurgensays:
August29,2012at11:24pm

Ihavethesameproblem.Ihavedownloadedthedemofile.Whenichangesomethinginthe
datasheetandjustclickontheupdatedropdownbutton.Itsnotpossibletosavethefileany
more.
ItsgivemethesameerrorYourchangescouldnotbesavedtoExcel_AsDatabasedemo
v1.xlsmbecauseofasharingviolation.Trysavingtoadifferentfile.

Alsotheproblemwhenyouchangesomethinginthedatasheet.clickresetandclickupdate
dropdownbutton.thanchooseproductsandshowdata.Itsgivingmetheolddata.The
databaseisnotbeenresetorreloaded.

Ifoundaworkaround:Updatethedatasheetwithyourquerythansaveclosethefileopenthe
fileandthanupdatedropdown.

Nowyouhavethefullfunctionality

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 17/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Reply

39. Binusays:
September13,2012at3:45pm

HiVijay,

CanyouprovidemetheVBAcodetoreadfrommultilpeexcelfilestoasingleexcelsheet

Thanks,
Binu

Reply

40. Luissays:
September19,2012at2:12pm

HiVijay,

Thanksforsharingthisworkwithusnovices.
Ihavemodifedthecomboboxnamestosuitmydatatablebutgetruntimeerror,typemismatchwhen
updatedropdownsbuttonispressed.

PrivateSubcmdUpdateDropDowns_Click()
strSQL="SelectDistinct[Card]From[data$]Orderby[Card]"
closeRS
OpenDB
cmbCard.Clear

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
cmbCard.AddItemrs.Fields(0)

rs.MoveNext
Loop
Else
MsgBox"IwasnotabletofindanyuniqueCard.",vbCritical+vbOKOnly
ExitSub
EndIf

Reply

41. bong25says:
September27,2012at8:19am

DearVijay,

Reallyhelpsmealotwiththis.

CouldyouhelpmehowtoaddcodeforManipulatingHeadingsofData.

WhatIwastryingtoachieveisasidefromthesampledata$(saysheet1),Ineedtodisplaydatasfrom
sheet2.Thecontentandheadingsarenotexactlythesame.

InshotIneedcodetomanipulateHeadingsfromdatathatIwastryingtoview.

Reply

42. Richardsays:
October11,2012at8:00am

AnewversionofExcelDatabaseTasksV2hasbeenreleased:pleaseseeblog

http://leansoftware.net/forum/enus/blog.aspx

Regards

Reply

43. Sebghatulbarysays:
http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 18/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
October22,2012at10:27am

ThankYouveryveryveryveryveryveryveryveryveryveryveryveryvery
Muchhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
itsreallyexcellent

Reply

44. Abdallasays:
October23,2012at5:06pm

Youarethebest.Igetsomuchoutofyourexamplesandexplanations.Iplanonsigningupforyourtraining
inthenextfewmonths.ButfirstIneedsomehelpforIprojectIamworkingon.Ihavedatatablesin
differenttabswithinthesameworkbook.HowdoIuseVBAorothertoolstogetthemtoexportthetabs
asAccesstableswithoutleavingExcel?AssumenoAccesstablesexistandthatIhavetwoscenariosfor
storingtheAccesstables:
1)Idothiseverymonthandwanttokeepthemonthlyaccesstablesseperate.
2)Idothiseverymonthandwanttoupdatethesametable.

Thanks.

Reply

45. JoJosays:
November1,2012at4:17am

HiJijay,

IhavelearnsomuchfromyourdemofileExcelasDatase.Ihavemotifiedthevbacodetofitmydatasetfor
mywork.However,IruntotheproblemwhenItrytosavethefileafterclickingthe"ShowData"button.
Itsgivemethesameerror"YourchangescouldnotbesavedtoExcel_AsDatabasedemov1.xlsmbecause
ofasharingviolation.Trysavingtoadifferentfile."Ihaveseenotherviewerspostthesameissuebut
havenotfoundasolutionbepostedyet.PleaseadvisehowIcanfixtheproblem?Thankyou.

Reply

46. Cho7tomsays:
November24,2012at4:26pm

Helloeveryone,

Thankyouforthismethod!

AnyanswerregardingLouis'sissue(postedonSept9th2012).

Iencounterthesamepb(runtimeerror13typemismatch).

Bestregards

Reply

VijaySharmasays:
November26,2012at11:07am

@Cho07tomandLouis,Pleaselookforblankrecordsinthecolumnthatyouaregettingasaresultof
theSQLquery,thisiscausingtheissue.Pleasetrythebelowcode


strSQL="SelectDistinct[Product]From[data$]Orderby[Product]"
closeRS
OpenDB
cmbProducts.Clear

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
IfNotIsNull(rs.Fields(0))ThencmbProducts.AddItemrs.Fields(0)
rs.MoveNext
Loop
Else
MsgBox"IwasnotabletofindanyuniqueProducts.",vbCritical+vbOKOnly

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 19/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
ExitSub
EndIf

Letmeknowifyouneedanyfurtherassistance.

~VijaySharma

Reply

Cho7tomsays:
December1,2012at10:55am

HelloVijay,

Itperfectlyworks!

Manythanksforyourhelp.

Regards,

cho7tom

Reply

kshitizsays:
February18,2014at5:07am

IkeepgettingtheerrorODBCdoesnotsupporttherequestedparameteserror2147217887at
theline
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic

Reply

47. OldFogeysays:
November26,2012at10:29am

Amtryingtousethismethodinmyworkbook.

Theexamplebookworksfine.

WhenIchangetomyownbook,however,Igeta446whenitisexecutingthecnn.ConnectionStringlinein
theOPENDBsub.

IhaveselectedtheactiveXlibraryinthereferences.

Anyideas?

Reply

OldFogeysays:
November26,2012at4:00pm

PleaseignorethepostImadeitisresolvednow.

Reply

48. OldFogeysays:
November26,2012at4:03pm

UsingSQLinExcelhowdoIaddressthecolumnsinasheetwithoutgivingeachcolumnaname?

Forexample,Ineedtoselectthe3rdand4thcolumnsofasheetanddonotwanttogivethemaname(as
thesheetsarefromreadonlyworkbookswhichdonothavenamedcolumns)

Ihavetried"Selectc,d..."whichdoesnotwork.

Reply

VijaySharmasays:
November28,2012at11:32am

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 20/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
@OldFogey,

Inthatcasethefirstrowistreatedascolumnheadings.

~VijaySharma

Reply

49. RoderickEsays:
November28,2012at4:28pm

IseealotofpeoplesayingExcelshouldn'tbeusedasaDByettheyneversaywhy.Tome,itseemsthey
justwanttokeepDBadministrationsocomplexthatitbecomesnecessarytokeepaDBadminonstaff.
Excel,isunderstoodbyalargergroupofpeopleandismoreapproachable.
Accesssometimescreatesunnecessaryduplicationwithmultiplereferencesspreadoutonmultipletables
whereaswithExcel,asimplecommonreferenceallowsforaleanerDB.
So,goodonyouVijaytoputforwardthatExcelcanbeusedasaDB.Aslongasyoucanarchiverarelyused
dataandthenhaveabilitytoretreiveit,thereshouldn'tbeaproblem.

Reply

50. HEertensays:
December4,2012at10:50am

Well,onereasontouseExcelasadatabaseiswhenyouruserboughtaHomeandStudentversionof
Office.TheydonthaveAccesstouseasadatabasebecauseit'snotincluded.Icanttellsomeonetobuy
Accessbecausetheymaynothavethefinancialmeanstodoso.Soforavery,verysimpleandsmall
databasesystem(about1500records)Excelwilldo.ItsnotasconvenientasAccess,butnevertheless
useful....

Reply

51. gowrishankarsays:
December11,2012at3:57pm

Iamanoncomputerbackground,amdoingaresearchinmedical(microbiology),ineedasimpledatabase
withexcelbackend,canusendthedetails...myrequirementisreceivingsampleandenteringtothe
databasewithidnumber&date,oftenlyihavetocheckwithidnumberwhethertheidnumberreceivedor
not.

Reply

Jaysays:
December11,2012at10:06pm

SoundslikeyoumeanttosayasimpledatabasewithexcelFrontEnd.
thatsaid,ifyouhaveasmalldataset,youcouldjustuseanexceltable(let'scallit
TableMyMicrobeDatatoholdthedata,andyourchartsorwhatever(pivottables?)woulduseasthe
source.

Otherwise,sinceitsoundslikeyouhaveoffice,youcoulduseanaccessdatabaseandadata
connectionviaMSQueryinexcel.bothhaveenough"visual"tools,youcouldcompleteyourdatabase
excelreportwithoutwritinganycodeatall.

Reply

52. Sumitsays:
December31,2012at10:49am

PleaseVijay,
canubealittlemorestepbystep,aslikeinothertutorialsonthissite.
iamtotallynewtothisSQLthingandwheneverutrytomakenewdatabase,asudid,ormodifyur
database,iamgettingerrors.

jstneedstepsashowtomodifybasicnamesandifsome1wanttoadd1morefilter/searchbox

thankyou.

Reply

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 21/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline

53. Richardsays:
January7,2013at12:45pm

Hi,
justtoletyouknowExceltodatabasehasbecome'ExcelDatabaseTask's(EDT)andallowsveryeasyData
EditofadatabaseTablefromExcel.
Pleaseseeblogfornewfeatures:
http://leansoftware.net/forum/enus/blog.aspx
Shortlytoincludedropdownlistsforrelationaldata.
Thankyoufortheinterest

Reply

54. Bramleysays:
January16,2013at7:22pm

HiChandoo,
IamnewtototallynewtoVBAoranyprogrammingforthatmatter,
IamusingExceltodomyQuotesandInvoices.Inthesameworkbook,Iwanttostartadatabasetoshowa
historyofquotesforthemonth/year,withoutlosinganydata.Iwouldalsoliketopossiblyaddamacrofor
whenIprintmyquote,toonlysavetheQuotationworksheetandnotthewholefile,butalsoupdatethe
databaseautomatically.
TheDatabasecouldalsobeusedtopullinformationforinvoicingpurposes.
WouldyourequiremetosendthroughmyworkbooksoyoucangetabetterunderstandingofwhatIam
talkingabout.
HowwouldIgoaboutdoingthis?
Yourhelpwillreallybeappreciated,Thanks.

Reply

55. LAURAsays:
January22,2013at4:10pm

Canibuyatemplateforthisss?
Ihavetriedtocreateit,startingontheVBAandMacrosstuffbutcouldntevenmakeacellgoredforsome
reason.
Thanks

Reply

56. Zubersays:
February6,2013at7:39pm

AwesomeJob.Ihavequestion.
inViewsheet.

Whenitputtsdataonsheetstartingfromrow12.
WhatistheeasiestwaytoSortbycolumnIthenG.


Thanksalotforsharing.

Reply

57. afshinsays:
March28,2013at8:40pm

Hi
MyEnglishisnotmydatabase.Andthereforeallitscharacters?Appear.WhatcanIdo?

Reply

58. afshinsays:
March29,2013at7:43pm

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 22/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
plz
helpme....
MyEnglishisnotmydatabase.Andthereforeallitscharacters?Appear.WhatcanIdo?

Reply

59. BobHolmessays:
April10,2013at6:27pm

IsthereanywaytohandlenullswithinaSQLstatementinExcelVBA?Itdoesnotrecognizethenz()
function

Reply

60. VinnyStackhousesays:
April13,2013at3:35pm

Lovethis!Inmanyofoursystemsandreports,weworkwithanOLAPdatabasecalledCognosTM1.Exceland
TM1Excelformulasarereallythemostcommoninterfacetothatdatabase.
BecauseofthatandthefactthatmostofourworkendsupbeinginExcelpagesitselfanyway,Icanreally
seeusingthisExcelasaDatabasefunctionalitybecomingreallyusefulforsomanyposibilities.Thisalsowill
finallyallowusnottobringinyetathirdapplicationplatformlikeAccessorOracleinourExcelDatamarts.

Reply

61. kumarsays:
April14,2013at3:51am

Iundersoodthelogicofconnectingthesheetsbutididntunderstandhowtobuildthesecondsheeti.e.view
sheet.......

Pleasehelpmeinbuildingthesecondsheet........ihavewrittenthecodeasyousaidinthispostbutunable
togetthefileasurshowinginthispost...
howtogettheviewpart.......

Reply

62. GaroudaHanoumansays:
April17,2013at7:50am

Thanksforthisnicetutorial.
Hopeyoudon'tmindifImakesomeremarks.

Iwouldhighlyrecommend:
1.NOneedofamoduleandaboveallNOPUBLICvariables,ifthereisanotherworkbookwiththesame
variablesyou'llgetanerror!
Moveyourcodefrom'module1'tothesheet'View'anddeclarethevariablelikethis:
OptionExplicit
DimcnnAsADODB.Connection'orPrivate...
DimrsAsADODB.Recordset
DimstrSQLAsString'couldberepeatedatProcedurelevel...
2.Otherchanges:
PrivateSubOpenDB()
Setcnn=NewADODB.Connection

PrivateSubcmdShowData_Click()
Setrs=NewADODB.Recordset

Eachtimeyouopenarecordset,disconnectit.Howmanyinstancesoftheconnectiondoyoucreate???
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Setcnn=Nothing'disconnecttherecordsetanddisposetheconnection

Ateachplacewhereyouexitasub,disposetherecordset!
Setrs=Nothing'disposetherecordset
ExitSub

StartusingadisciplineinprogrammingthatfollowstheOOPrules...
Hopeithelps,

BestWishes,

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 23/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Bernard

Reply

63. GaroudaHanoumansays:
April17,2013at8:16am

Anotherpoint:
Youwillseethattheformatisnotthesame,no$signafterafewrows,differentalignment...
Thiswillhelp:
'Nowputtingthedataonthesheet
ActiveCell.CopyFromRecordsetrs
'Addthistohavethesameformat
WithRange("dataSet")
.Select
.Copy
EndWith
Range(Selection,Selection.End(xlDown)).PasteSpecial(xlPasteFormats)
Application.CutCopyMode=False'cleartheclipboard
Range("dataSet").Select

BestWishes,

Garouda.

Reply

64. GaroudaHanoumansays:
April17,2013at3:16pm

Well,Ifearsomepeoplemaygetconfused.Iprefertogivethewholecodehere.
remark:removemodule1

OptionExplicit
DimcnnAsADODB.Connection
DimrsAsADODB.Recordset
DimstrSQLAsString

PrivateSubOpenDB()
Setcnn=NewADODB.Connection
Ifcnn.State=adStateOpenThencnn.Close
cnn.ConnectionString="Driver={MicrosoftExcelDriver(*.xls,*.xlsx,*.xlsm,*.xlsb)};DBQ="&_
ActiveWorkbook.Path&Application.PathSeparator&ActiveWorkbook.Name
cnn.Open
EndSub

PrivateSubcmdReset_Click()
'clearthedata
cmbProducts.Clear
cmbCustomerType.Clear
cmbRegion.Clear
Sheets("View").Visible=True
Sheets("View").Select
Range("dataSet").Select
Range(Selection,Selection.End(xlDown)).ClearContents
EndSub

PrivateSubcmdShowData_Click()
Setrs=NewADODB.Recordset
'populatedata
strSQL="SELECT*FROM[data$]WHERE"
IfcmbProducts.Text""Then
strSQL=strSQL&"[Product]='"&cmbProducts.Text&"'"
EndIf

IfcmbRegion.Text""Then
IfcmbProducts.Text""Then
strSQL=strSQL&"AND[Region]='"&cmbRegion.Text&"'"
Else
strSQL=strSQL&"[Region]='"&cmbRegion.Text&"'"
EndIf
EndIf

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 24/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
IfcmbCustomerType.Text""Then
IfcmbProducts.Text""OrcmbRegion.Text""Then
strSQL=strSQL&"AND[CustomerType]='"&cmbCustomerType.Text&"'"
Else
strSQL=strSQL&"[CustomerType]='"&cmbCustomerType.Text&"'"
EndIf
EndIf

IfcmbProducts.Text""OrcmbRegion.Text""OrcmbCustomerType.Text""Then
'nowextractdata

OpenDB

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Setcnn=Nothing
Ifrs.RecordCount>0Then
Sheets("View").Visible=True
Sheets("View").Select
Range("dataSet").Select
Range(Selection,Selection.End(xlDown)).ClearContents

'Nowputtingthedataonthesheet
ActiveCell.CopyFromRecordsetrs
WithRange("dataSet")
.Select
.Copy
EndWith
Range(Selection,Selection.End(xlDown)).PasteSpecial(xlPasteFormats)
Application.CutCopyMode=False
Range("dataSet").Select
Else
MsgBox"Iwasnotabletofindanymatchingrecords.",vbExclamation+vbOKOnly
Setrs=Nothing
ExitSub
EndIf

'NowgettingthetotalsusingQuery
IfcmbProducts.Text""AndcmbRegion.Text""AndcmbCustomerType.Text""Then
strSQL="SELECTCount([data$].[CallID])AS[CountOfCallID],[data$].[Resolved]"&_
"FROM[Data$]WHERE((([Data$].[Product])='"&cmbProducts.Text&"')And"&_
"(([Data$].[Region])='"&cmbRegion.Text&"')And(([Data$].[CustomerType])='"&
cmbCustomerType.Text&"'))"&_
"GROUPBY[data$].[Resolved];"

OpenDB
rs.Close
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Setcnn=Nothing
Ifrs.RecordCount>0Then
Range("L6").CopyFromRecordsetrs
Else
Range("L6:M7").Clear
MsgBox"Therewassomeissuegettingthetotals.",vbExclamation+vbOKOnly
Setrs=Nothing
ExitSub
EndIf
EndIf
EndIf
rs.Close
Setrs=Nothing
EndSub

PrivateSubcmdUpdateDropDowns_Click()
strSQL="SelectDistinct[Product]From[data$]Orderby[Product]"

OpenDB
cmbProducts.Clear
Setrs=NewADODB.Recordset

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Setcnn=Nothing
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
cmbProducts.AddItemrs.Fields(0)
rs.MoveNext

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 25/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Loop
Else
MsgBox"IwasnotabletofindanyuniqueProducts.",vbCritical+vbOKOnly
Setrs=Nothing
ExitSub
EndIf

'
strSQL="SelectDistinct[Region]From[data$]Orderby[Region]"

OpenDB
cmbRegion.Clear
rs.Close
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Setcnn=Nothing
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
cmbRegion.AddItemrs.Fields(0)
rs.MoveNext
Loop
Else
MsgBox"IwasnotabletofindanyuniqueRegion(s).",vbCritical+vbOKOnly
Setrs=Nothing
ExitSub
EndIf
'
strSQL="SelectDistinct[CustomerType]From[data$]Orderby[CustomerType]"

OpenDB
cmbCustomerType.Clear
rs.Close
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Setcnn=Nothing
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
cmbCustomerType.AddItemrs.Fields(0)
rs.MoveNext
Loop
Else
MsgBox"IwasnotabletofindanyuniqueCustomerType(s).",vbCritical+vbOKOnly
Setrs=Nothing
ExitSub
EndIf
rs.Close
Setrs=Nothing
EndSub

BestWishes,

Garouda

Reply

65. GaroudaHanoumansays:
April17,2013at3:45pm

Inoticedanotherpotentialissue.
Thecomboboxesaresetas0fmStyleDropDownCombo.
LookatProperties,Style,inDesignMode...
Thisenablestheusertoaddsomeiteminthecombo.
IwouldrewritetheResetcodelikethis:
PrivateSubcmdReset_Click()
'clearthedata
cmbProducts.Clear
cmbProducts.Text=vbNullString'incaseauserwrotesomething
cmbCustomerType.Clear
cmbCustomerType.Text=vbNullString
cmbRegion.Clear
cmbRegion.Text=vbNullString
Sheets("View").Visible=True
Sheets("View").Select
Range("dataSet").Select
Range(Selection,Selection.End(xlDown)).ClearContents

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 26/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Me.[C4].Select'novisibleselection
EndSub

BestWishes,

Garouda

Reply

DeekshaBalujasays:
March21,2016at11:08am

HeyGaroudaHanouman,

WouldyoupleasepleaseexplainastowhatisME.[C4].SELECT

Thanksalotinadvance

Reply

66. Colinsays:
April18,2013at3:33pm

Isthereawaytosolvetheissuethatpreventssaving.IgetasharingviolationifItrytosavethefileafter
makingchanges.ShouldIimplementthedatabasebasedonthecommentsfromGarouda?

Reply

67. Colinsays:
April18,2013at4:16pm

Garouda,yourcodeworkedandIcannowsavethefile.

Thanksforpostingit.

Reply

68. GaroudaHanoumansays:
April19,2013at7:07am

HiColin,
Onepossiblereasonisthatthefileis'readonly'.Whatyouhavetodoistosaveitunderanothername.

!Onelittlechangeinthecode:toavoidanyproblem,itwouldbebettertoreplace
rs.close
by
Ifrs.State=adStateOpenThenrs.Close
attheendoftheprocedure
cmdShowData_Click

Indeed,ifyoudonotselectanythingandclickonthecommandbuttonShowData,it'llgenerateanerror.

Basicallytheprogramshouldhavesomesafetyfeaturestopreventthis.
I'llmadesomechangesinordertotakethatintoaccount...
Anotherremark,IneverdeclarevariablesatmodulelevelifIcanavoidit.Declarethematprocedurelevel
eachtimeyoucan.YouwillseethatIsendtheconnectiontotheOpenDBprocedureByReferenceByRef.
Therearetwopossibilities:ByValorByRef,ByRefisthedefaultvalueinVBAandVB6,notinVB.Netanymore.
Inthiscase,onlyByRefispossible.ByValsendsacopyofthevariabletoaprocedureorafunctionwhere
ByRefworkslikeapointerinCorC++.ByReftellstheprogrammewheretofindtheobjectinthecomputer
memory...
I'mgoingtocopythewholemodifiedcodeagaininanextpost.
Trytoclickon'ShowData'inmypreviouscode,withoutselectinganything,andtryitwiththenewcode.

Cheers,

Garouda

Reply

69. GaroudaHanoumansays:
April19,2013at7:13am

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 27/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Herethemodifiedcode,morebulletproof...

Cheers,

Garouda

DonotforgettoremoveModule1andreplacethecodeinthesheet'View'withthisone:

OptionExplicit
DimniFlagAsInteger

PrivateSubOpenDB(ByRefcnnAsADODB.Connection)
'notethechangebetweenbracketsByRefcnnAs...
cnn.ConnectionString="Driver={MicrosoftExcelDriver(*.xls,*.xlsx,*.xlsm,*.xlsb)};DBQ="&_
ActiveWorkbook.Path&Application.PathSeparator&ActiveWorkbook.Name
cnn.Open
EndSub

PrivateSubcmdReset_Click()
'clearthedata
cmbProducts.Clear
cmbProducts.Text=vbNullString
cmbCustomerType.Clear
cmbCustomerType.Text=vbNullString
cmbRegion.Clear
cmbRegion.Text=vbNullString
Sheets("View").Visible=True
Sheets("View").Select
Range("dataSet").Select
Range(Selection,Selection.End(xlDown)).ClearContents
Me.[C4].Select'moreprofessional:theactivecellishidden...
niFlag=0
EndSub

PrivateSubcmdShowData_Click()
'it'salwaysbettertodeclaresuchvariablesatprocedurelevel
DimstrSQLAsString
DimcnnAsADODB.Connection
DimrsAsADODB.Recordset
IfniFlag=0Then
MsgBox"PleasepopulatethelistsfirstclickonUpdateDropDowns!",vbOKOnly+vbExclamation,
"ExcelandADODB"
ExitSub
EndIf
IfcmbProducts.Text=vbNullStringAndcmbCustomerType.Text=vbNullStringAndcmbRegion=
vbNullStringThen
MsgBox"Selectatleastoneitem!",vbOKOnly+vbExclamation,"ExcelandADODB"
ExitSub
EndIf
Application.ScreenUpdating=False
'createanewinstanceoftherecordset
Setrs=NewADODB.Recordset
'populatedata
strSQL="SELECT*FROM[data$]WHERE"
IfcmbProducts.Text""Then
strSQL=strSQL&"[Product]='"&cmbProducts.Text&"'"
EndIf

IfcmbRegion.Text""Then
IfcmbProducts.Text""Then
strSQL=strSQL&"AND[Region]='"&cmbRegion.Text&"'"
Else
strSQL=strSQL&"[Region]='"&cmbRegion.Text&"'"
EndIf
EndIf

IfcmbCustomerType.Text""Then
IfcmbProducts.Text""OrcmbRegion.Text""Then
strSQL=strSQL&"AND[CustomerType]='"&cmbCustomerType.Text&"'"
Else
strSQL=strSQL&"[CustomerType]='"&cmbCustomerType.Text&"'"
EndIf
EndIf

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 28/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
IfcmbProducts.Text""OrcmbRegion.Text""OrcmbCustomerType.Text""Then
'nowextractdata
'createanewinstanceoftheconnection
Setcnn=NewADODB.Connection
'notethatwehavetoaddcnn
OpenDBcnn
'createtherecordset
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
'disposetheconnectionanddisconnecttherecordset
Setcnn=Nothing
'DONOTclosetheconnectionhereasit'llclosetherecordsetaswell
Ifrs.RecordCount>0Then
Sheets("View").Visible=True
Sheets("View").Select
Range("dataSet").Select
Range(Selection,Selection.End(xlDown)).ClearContents

'Nowputtingthedataonthesheet
ActiveCell.CopyFromRecordsetrs
WithRange("dataSet")
.Select
.Copy
EndWith
Range(Selection,Selection.End(xlDown)).PasteSpecial(xlPasteFormats)
Application.CutCopyMode=False
Me.[C4].Select
Else
MsgBox"Iwasnotabletofindanymatchingrecords.",vbExclamation+vbOKOnly
Setrs=Nothing
ExitSub
EndIf

'NowgettingthetotalsusingQuery
IfcmbProducts.Text""AndcmbRegion.Text""AndcmbCustomerType.Text""Then
strSQL="SELECTCount([data$].[CallID])AS[CountOfCallID],[data$].[Resolved]"&_
"FROM[Data$]WHERE((([Data$].[Product])='"&cmbProducts.Text&"')And"&_
"(([Data$].[Region])='"&cmbRegion.Text&"')And(([Data$].[CustomerType])='"&
cmbCustomerType.Text&"'))"&_
"GROUPBY[data$].[Resolved];"

Setcnn=NewADODB.Connection
OpenDBcnn
rs.Close
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Setcnn=Nothing
Ifrs.RecordCount>0Then
Range("L6").CopyFromRecordsetrs
Else
Range("L6:M7").Clear
MsgBox"Therewassomeissuegettingthetotals.",vbExclamation+vbOKOnly
Setrs=Nothing
ExitSub
EndIf
EndIf
EndIf
rs.Close
Setrs=Nothing
Application.ScreenUpdating=True
EndSub

PrivateSubcmdUpdateDropDowns_Click()
DimstrSQLAsString
DimcnnAsADODB.Connection
DimrsAsADODB.Recordset
niFlag=1
strSQL="SelectDistinct[Product]From[data$]Orderby[Product]"
Setcnn=NewADODB.Connection
OpenDBcnn
cmbProducts.Clear
Setrs=NewADODB.Recordset
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Setcnn=Nothing
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
cmbProducts.AddItemrs.Fields(0)
http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 29/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
rs.MoveNext
Loop
Else
MsgBox"IwasnotabletofindanyuniqueProducts.",vbCritical+vbOKOnly
Setrs=Nothing
ExitSub
EndIf

strSQL="SelectDistinct[Region]From[data$]Orderby[Region]"

Setcnn=NewADODB.Connection
OpenDBcnn
cmbRegion.Clear
rs.Close
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Setcnn=Nothing
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
cmbRegion.AddItemrs.Fields(0)
rs.MoveNext
Loop
Else
MsgBox"IwasnotabletofindanyuniqueRegion(s).",vbCritical+vbOKOnly
Setrs=Nothing
ExitSub
EndIf
'
strSQL="SelectDistinct[CustomerType]From[data$]Orderby[CustomerType]"

Setcnn=NewADODB.Connection
OpenDBcnn
cmbCustomerType.Clear
rs.Close
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Setcnn=Nothing
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
cmbCustomerType.AddItemrs.Fields(0)
rs.MoveNext
Loop
Else
MsgBox"IwasnotabletofindanyuniqueCustomerType(s).",vbCritical+vbOKOnly
Setrs=Nothing
ExitSub
EndIf
Ifrs.State=adStateOpenThenrs.Close
Setrs=Nothing
EndSub

Reply

Michaelsays:
July18,2013at2:06pm

Garouda,Vijay,etal...

Funtionalitywith"bulletproof"codemodworksgreatwithupdatingmultiplecomboboxeswith
independentcriteria.Unfortunately,I'mhavingabitofdificultytryingtousethebasecodeto
sequentiallyupdatethecomboboxesusingcriteriafromthepreviouslyupdatedbox.

Mycode:
'
OptionExplicit
DimniFlagAsInteger

PrivateSubOpenDB(ByRefcnnAsADODB.Connection)
cnn.ConnectionString="Driver={MicrosoftExcelDriver(*.xls,*.xlsx,*.xlsm,*.xlsb)}DBQ="&_
ActiveWorkbook.Path&Application.PathSeparator&ActiveWorkbook.Name
cnn.Open
EndSub

PrivateSubWorksheet_SelectionChange(ByValTargetAsRange)

EndSub
http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 30/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
PrivateSubWorksheet_Activate()
DimstrSQLAsString
DimcnnAsADODB.Connection
DimrsAsADODB.Recordset
niFlag=1
strSQL="SelectDistinct[CMD]From[data$]Orderby[CMD]"
Setcnn=NewADODB.Connection
OpenDBcnn
Me.Cmb_CMD.Clear
Setrs=NewADODB.Recordset
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Setcnn=Nothing
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
Me.Cmb_CMD.AddItemrs.Fields(0)
rs.MoveNext
Loop
Else
MsgBox"IwasnotabletoidentifyRegionalMedicalCommands.",vbCritical+vbOKOnly
Setrs=Nothing
ExitSub
EndIf

EndSub

PrivateSubCmb_CMD_Change()
DimstrSQLAsString
DimcnnAsADODB.Connection
DimrsAsADODB.Recordset
niFlag=1
strSQL="SelectDistinct[MTF]From[data$]Where[CMD]='"&Cmb_CMD.Text&"'Orderby[MTF]"
Setcnn=NewADODB.Connection
OpenDBcnn
Me.Cmb_MTF.Clear
Setrs=NewADODB.Recordset
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Setcnn=Nothing
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
Me.Cmb_MTF.AddItemrs.Fields(0)
rs.MoveNext
Loop
Else
MsgBox"IwasnotabletoidentifyParentMTF(s).",vbCritical+vbOKOnly
Setrs=Nothing
ExitSub
EndIf

EndSub
'

The"PrivateSubWorksheet_Activate()"operationisflawless.WhenImakeaselectioninthe
"Cmb_CMD"box,the"PrivateSubCmb_CMD_Change()"operationerrorsoutwitha"Runtimeerror
'2147217887(80040e21)':ODBCdriverdoesnotsupporttherequestedproperties."onthe"rs.Open
strSQL,cnn,adOpenKeyset,adLockOptimistic"line.

Qupasaconeso?

Reply

AmitPsays:
February12,2014at10:37am

Michaeldidyougotanysolutiontothiscode/Runtimeerror,ifyescouldyouplsshareittome.

Reply

vickysays:
June6,2016at1:59pm

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 31/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
HiAmit,

Iamstuckincombinetwotables"TableAandTableB"
Iamtryingselect*from[TableA$]A,[TableB]BwhereA.id=B.id
Isthisarightway..?

Reply

70. excelersays:
May8,2013at10:47pm

Needstomakelittllecorrectioninsourceincaseifyouneedtoseealldata:strSQL="SELECT*FROM
[data$]WHERE"insteaduse
strSQL="SELECT*FROM[data$]"andmovewheretoifstatement
change.

Plusitaddsnovaluetoexcelfilter.
ThismaybeusedwhenOR,Joinfunctionalityisneededfromdatabase.butMSquerymuchmoredynamicand
lesscumbersome.

Reply

Antoniosays:
October29,2015at6:32pm

ExactlywhatpartoftheifstatementdoestheWHEREgo.

Reply

71. Marcsays:
May15,2013at2:17pm

ThisisagreatarticleasalwaysandIthinkitcouldreallyhelpwitharegularreportIneedtosetupinwork.
CouldyouhelpbytellingmehowIcouldaddasecondtableandlinkbothusingauniqueidentifier?

Reply

72. Mohammadhassanisays:
June2,2013at10:54am

hiChandoo,

Manythanksforyourefforts.

iusethiscodsinmyprojectbutigotaerrorwhenwanttoupdatecomboboxesvalueTypemismatchas
below:

PrivateSubcmdUpdate_Click()
'UpdatingConsigneeFilds
strSQL="SelectDistinct[Client]From[data$]Orderby[Client]"
closeRS
OpenDB
cmbConsignee.Clear

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
cmbConsignee.AddItemrs.Fields(0)==>typemismatche
rs.MoveNext
Loop
Else
MsgBox"IwasnotabletofindanyuniqueConsignee.",vbCritical+vbOKOnly
ExitSub
EndIf
.
.
.

Reply

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 32/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline

73. Mohammadhassanisays:
June2,2013at12:02pm

dearGaroudaHanouman,

yourlastCoddon'tworkigoterrorforline:

IfcmbProducts.Text""Then"

compilererror
syntaxerror

plsadvise...

Reply

NairBsays:
June5,2013at7:55pm

Fantastictutorial
@GaroudaHanouman
Ialsohavethesameerrorwithyouralternativecodewhenpopulatingdata:

IfcmbProducts.Text""Then

Reply

NairBsays:
June5,2013at9:23pm

Ifixedit....

Codewasmissingoperators.Itshouldread....

IfcmbProducts.TextThen

Reply

Tonysays:
October28,2015at6:07pm

Istillhaveanerrorwhenpopulatingdata:
IfcmbProducts.TextThen

Reply

74. Mohammadhassanisays:
June3,2013at4:18am

againme!!

ijustreceivedbelowerrorcananyonehelpmetosorteditout?

[Microsoft][ODBCExcelDrive]theconnectionforviewingyourlinkedMicrosoftExcelworksheetwaslost.

thanks.

Reply

75. Mohammadhassanisays:
June3,2013at12:03pm

higuys

allmylastproblemwassortedoutnowjusthaveaquestion:

howwecouldshowsomeofdataondatasetonsheetviewnotallofdata?

Reply

DeekshaBalujasays:
http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 33/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
March22,2016at7:05am

HeyMohammad,

couldyoupleasetellme,howdidyoumanagetosolvetheUpdatedropdownproblem?

Reply
76.Helpmeapplyanonlineexcelasadatabasemacrotomyspreadsheetsays:
June3,2013at2:05pm

[...]ignorantwhenitcomestoVBAsocansomeonepointmeattherightdirection.Here'sthetutorialUsing
ExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline.WhatIneedtoapplyittomy
spreadsheetisawaytonotonlyselectfromthedynamiclists,[...]

Reply

77. Mohammadhassanisays:
June8,2013at9:55am

HIALL

pleasehelpmehowicouldchosedatabetween2dateorafteradateorbeforeadate?

thanks

Reply

78. Frostsays:
July19,2013at6:10pm

Hi,
Istillfindnodifferencebetweenthisdemooffilteringandthenormalfilteringinexcel,DATA>Filter.youget
thesameresults,justinadifferentworksheet.
Cansomoneexplainthistomeplease?

Reply

79. SUMITGUPTAsays:
August5,2013at10:56am

anybodycanresolvemyproblem.ihaveasheetandusefilteron6rowsoutof15rows.incolumnause
someformula.butwheniopenthefilterAcellsamountwillchange.
myqueryishowtocopythefilterdcelldataandpasteinsamecells.
columnAformulausedsubtotal(3,b$2:b2)
ABC
no.idcountif
1IN10000481
2IN10000551
IN10000563
IN10000562
5IN10000561
IN10000572
7IN10000571
8IN10001031
IN10001573
IN10001572
11IN10001571
IN10001643
IN10001642
14IN10001641
IN10001822
16IN10001821
IN10002152
18IN10002151
IN10002402
20IN10002401

AFTERFILTER
ABC
no.idcountif
1IN10000481
http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 34/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
2IN10000551
3IN10000561
4IN10000571
5IN10001031
6IN10001571
7IN10001641
8IN10001821
9IN10002151
10IN10002401

PLEASERESOLVEMYQUERYTHANKS

Reply

80. Topesays:
August21,2013at7:10am

Hi.

I'mhavingsomeproblemswiththecode,Ithinkit'sbecausei'msittingonaWindowsServer(2003).When
i'mtryingtoupdatetheDropDownlistigetthisErrorcode(Can'tfindprojectorlibrary)

Ialsofoundoutthati'mmissigthe:
MicrosoftActiveXDataObjects6.0Library,thelatestversionihaveis
MicrosoftActiveXDataObjects2.7Library.

isitpossibletomakethecodework?

Reply

Topesays:
August21,2013at7:18am

Isolvedit.

iforgottouncheckthe:
MISSING:MicrosoftActiveXDataObjects6.0Library
beforeicheckedthe
MicrosoftActiveXDataObjects2.7Library.

Reply

81. VanessaLambertsays:
August22,2013at3:45pm

WhenIopenthedocumenttoplayaround,itsaysthatthereisanerrorandneedstobedebugged.Anyone
knowwhythelinkisnotworkingorwhatcouldbedonetofixit?

Thanks!

Reply

82. afshin160says:
August25,2013at11:02am

HI.
howisADOB,Delet,update,insertsupport?

Reply

83. DickByrnesays:
September17,2013at6:07pm

Vijay,
Justranacrossyourarticleandfounditinteresting.AfewmonthsbackIhadasituationthatforcedmeto
"learnbytrying"thesamebasictechnique.Ihavedatainspreadsheets(verylargeontheorderof90,000
rows).Neededtodosomedataconversionsonsomeofthecolumnsviaaseparatelookupspreadsheet(e.g.
lookup'BusinessUnit'inthebigspreadsheetandcreateacolumncalled'DashboardOrg'basedonalookup
table).

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 35/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Becausethesourcedatahassomanyrows,usinganexcelformula(actuallyseveralasthereweremultiple
lookuptablesinvolved)causedthespreadsheetrecalctimetogothroughtheroof.

SolvedtheproblemusingtheODBCExceldriverandsomebasicSQL.Yes,youcanuseSQLagainstanExcel
workbook.Infact,youcandoallkindsofgoodthingsviatheODBCdriverouterjoinsagainstmultiple
workbooks,usingSQL'sscalarfunctions,etc.

HereisanexampleofSQLthatjoinsdatafrom5differentworkbooksintoasingleworksheet:

SELECTIMDATA.*,
BU.[DashboardOrg],
BU.[NewCU]AS"CustomerUnit",
BU.[NewBusinessUnit]AS"BusinessUnit",
AG.[ReportingGroup]
FROM((SELECTIM.*,
FORMAT(IM.[CreateDate/Time],'YYYYMM')AS"MonthOpened",
FORMAT(IM.[ServiceRestoredDate/Time],'YYYYMM')AS"MonthServiceRestored",
IIF(IM.[ServiceRestoredDate/Time]ISNULL,NULL,
DATEDIFF('s',IM.[CreateDate/Time],IM.[ServiceRestoredDate/Time])/3600.0)
AS"HrsToServiceRestored",
IIF(IM.[ServiceRestoredDate/Time]ISNULL,NULL,
IM.[TotalDurationHours]
IIF(IM.[ServiceRestoredHours]ISNULL,0,IM.[ServiceRestoredHours])
IIF(IM.[SuspendHours]ISNULL,0,IM.[SuspendHours]))
AS"SLAHours",
LOCTBL.[NewBusinessUnit]AS"LocationBU",
SEV1.BUAS"Sev1BU",
SEV1.[ResponsibleParty],
SEV1.[ServiceArea],
SEV1.[WKCauseCode],
SEV1.[ProblemShortDescription],
IIF(SEV1.BUISNULL,
IIF(IM.[CIBU]ISNULL,
IIF(LOCTBL.[NewBusinessUnit]ISNULL,
'Unknown',
LOCTBL.[NewBusinessUnit]),
IM.[CIBU]),
SEV1.BU)
AS"SelectedBU"

FROM((`C:\Users\DickByrne\Documents\ITOCustomerService\BUMetrics\BUReports\201308\Source
Data\IncidentsODBCv2.xlsx`.`Incidents$`ASIM
LEFTOUTERJOIN`C:\Users\DickByrne\Documents\ITOCustomerService\BUMetrics\BUReports\2013
08\Sev13yearTrendAnalysis.xlsm`.`Data$`ASSEV1
ONIM.[IncidentID]=SEV1.[IncidentID])
LEFTOUTERJOIN`C:\Users\DickByrne\Documents\ITOCustomerService\BUMetrics\References\DivCUBU
LocNameMappingfor2013.xlsx`.`'DellLocationCodes$'`ASLOCTBL
ONIM.Location=LOCTBL.[LocationName+])
)ASIMDATA

LEFTOUTERJOIN`C:\Users\DickByrne\Documents\ITOCustomerService\BUMetrics\References\DivCUBU
LocNameMappingfor2013.xlsx`.`'BULookup$'`ASBU
ONIMDATA.[SelectedBU]=BU.[OriginalBusinessUnit])
LEFTOUTERJOIN`C:\Users\DickByrne\Documents\ITOCustomerService\BUMetrics\References\Assignee
GroupAlignment.xlsx`.`'AssigneeGroupMapping$'`ASAG
ONIMDATA.[AssigneeGroup]=AG.AssigneeGroup

WHERE(IMDATA.[AffectedItemName]NOTLIKE'Update%')AND(IMDATA.[SeverityNumber]<=4)

Prettycoolstuff!

Reply

84. Anandsays:
September20,2013at6:47pm

HelloVijay,

Thanksforpostingthisarticle.Afterreadingthisarticle,Isuccessfullydevelopedanexcelbasedtoolusing
ADOtoanalysecustomerissues.Iverymuchappreciateyourtimeandeffortsinwritingthearticleandmore

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 36/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
importantlysharingthecodeintheExcelfile.
Thissiteisgreat.Greatwork!keepitup!!

Anand

Reply
85.IsaidyourspreadsheetisreallyFAT,notrealPHAT!|Chandoo.orgLearnMicrosoftExcelOnlinesays:
September29,2013at11:43pm

[]alsohasagreatguestpostbyVijayUsingExcelAsYourDatabaseonthissubject.Igroreallthe
naysayersinthecommentswhosayExcel[]

Reply

86. Msquared99says:
October11,2013at5:55pm

AfterlookingatthisarticleIhaveponderedtheideaofstoringthedatainAccessasatablethenusingExcel
toextractthedataasselectedinsteadofbuildingqueriesandreportsinAccess.

IalreadyhaveamacrothatpullsdatafromAccessandplacesitintoExcel.AllIwouldhavetodoismodifya
little.

Thoughts,ideas?

Reply

87. Mohammadhassanisays:
October21,2013at6:09am

hi

Ireceivedbelowerror:

Runtimeerror'2147217906(80040e0e)':

[Microsoft][ODBCExcelDriver]Invalidbookmark

andbelowlinebehighlighted:

ActiveCell.CopyFromRecordsetrs

plsanyonehelpmetofixit.

Reply

88. Debsays:
October28,2013at1:36pm

Thisisanawsomearticle.Thishassolvedmanyproblemswithoutusingaccess.

Thanksalot

Reply

89. AmarRanjanDassays:
November23,2013at6:35pm

Hi,Ihavegonethroughyourcodeandapplication,itisreallyagreathelp!

IamtryingtodevelopaapplicationusingthesqlquerywhereIneedtoexecutetheupdatequery,butIam
unabletoexecutethequery,

Myqueryislikeasbelow,

strSQL="UPDATElocation_details$SET[location_details$].[SCANR_ID]='"&scanr_id&"',
[location_details$].[SCAN_CAPACTY]='"&scanr_capacty&"'WHERElocation_details$.[LOC_ID]='"&locId&
"'ANDlocation_details$.[REG_ID]='"&region&"'"

ButIamgettingsomeerrorlike,

a)syntaxerrorinUPDATEstatement
b)HowIwillexecutetheupdateorinsertquery
http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 37/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
pleasehelpme.

ThanksinAdvance

Reply

90. chrissays:
December18,2013at5:17pm

Itriedthisandamgettinga(runtimeerror)thebelowerroronline
Range("dataSet").Select
notsurewhatiammissing.anyhelpwillbemuchapreciated
canoneofyouhelpmeresolvethis?

Runtimeerror'1004'
method'Range'ofobject'_Worksheet'failed

Cheers
Chris

Reply

91. JeffSlavinsays:
January12,2014at2:41am

Iusedyourcode,butmodifiedtheOpenDBfunctiontoreadfromaseparatedatafileworkbook.Codeworked
greatBUT.....

Afterthecoderuns,iclosetheconnections(bycallingthecnnandrsClose()functions)andthensetboth
variablestonothing.

Afterthat,ifIgotothedatafileandtrytoopenit,igetthe'FileInUse'messageanditsaysicanonlyopen
sReadOnly.ItappearsthatExcelthinksthedatafileisstillinuse,eventhoughI'veclosedtheconnections.

Anythoughtsorhelp?

Reply

92. JeffSlavinsays:
January12,2014at6:38am

canyougiveanexampleofwritingtothedatabase(eg.usingUPDATEsqlcommand)??

Reply

93. Richardsays:
January12,2014at10:37am

Hithere,

WehavecreatedanewHowTopagethatexplainsindetailhowtoimportdatafromExcelspreadsheetsusing
themostrobusttechniqueinworld!

http://leansoftware.net/forum/enus/help/exceldatabasetasks/workedexamples/howtoimportexcel
spreadsheettosqlserverdata.aspx

Richard

Reply

94. AmitPsays:
February7,2014at11:42am

IhavequestionhereiswithtwocolumnsoneisProductandanotherisregionandasfarasdatainboth
columnsisconcernedisbasicallyRegionandProduct.Fore.g.InProductcolumnihavecountrynameslike
Accessories,Desktop,LaptopandMiscandagainstsameProductnamesIhaveregionasEastinRegion
column.

WhatIwant:IncomboboxIwanttopopulateregionnames(whichisalreadydoneandworksfine)andin
2ndcomboboxIwanttopopulateProductnamesonthebasisofregionselection.fore.g.IfIselectregionas

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 38/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
EastinmyComboboxthenmy2comboboxshouldgetpopulatedwithonlyProduct.i.eDesktop,Laptop,
Misc.

Reply

95. Chrissays:
March4,2014at6:30am

DearVijay,

Iencounteredsomeerrors.Wheniclick"UpdateDropdownList",errormessagepopsupsaying:"[Microsoft]
[ODBCExcelDriver]Toofewparameters.Expected1"andhighlighted(rs.OpenstrSQL,cnn,adOpenKeyset,
adLockOptimistic).Pleasehelpmewiththisproblem.Hereismycode.

strSQL="SelectDistinct[Classification]From[BookDatabase$]Orderby[Classification]"
closeRS
OpenDB
cboSearch.Clear

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
cboSearch.AddItemrs.Fields(0)
rs.MoveNext
Loop
Else
MsgBox"Can'tfinduniqueclassification.",vbCritical+vbOKOnly
ExitSub
EndIf

Reply

96. Deansays:
March13,2014at6:00am

IalsohadthesharingviolationerroronmyWindows764bit,butIhavesolveditbychangingthedatabase
referencefromMSDASQLtoJet:

'NEWWAYtoconnect:
PublicSubopen_db()

close_db

Setcn=NewADODB.Connection
Withcn
.Provider="Microsoft.Jet.OLEDB.4.0"
.ConnectionString="DataSource="&ActiveWorkbook.FullName&"ExtendedProperties=Excel8.0"
.Open
EndWith
EndSub

'BELOWISTHE*OLD*WAY(whichgeneratedthesharingviolation)
DimcnasADODB.Connection
Setcn=NewADODB.Connection
Withcn
.Provider="MSDASQL"
.ConnectionString="Driver={MicrosoftExcelDriver(*.xls)}"&_
"DBQ=C:\MyFolder\MyWorkbook.xlsReadOnly=False"
.Open
EndWith

Reply

97. Raymondsays:
March26,2014at7:12pm

Hello,
IamnewinVB,Icanunderstandyourprogramperfectly.Icouldnotunderstandthisdataset,couldyou
pleaseexplainittome?
Range("dataSet").Select

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 39/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Thankyou,
Raymond

Reply
98.VBASerenity|Chandoo.orgLearnMicrosoftExcelOnlinesays:
March31,2014at8:00am

[]BeyondExcel:VBAandDatabaseManipulationblog.ChandooalsohasagreatguestpostbyVijayUsing
ExcelAsYourDatabaseonthissubject.Ignoreallthenaysayersandunbelieversinthecommentswhosay
"Excelshalt[]

Reply

99. renesays:
April8,2014at7:02am

Hi,

iworkwiththisamazingfeaturenowforawhile.buttomakethingsworkevenbetteridobitwisesearches
onmarkedcategories.however,icannotgetthistoworkinexcel..
thewhereparthangs:

"WHERECAST([group_desc$].[category_id1]asUNSIGNEDINTEGER)&10"

Anyideaanyone?orisitjustexcelthatdoesnotlikethis.

Regards,

Rene

Reply

100. renesays:
April8,2014at7:03am

sorry,
missingthethere..

Reply

101. Adamsays:
April8,2014at12:27pm

Hiall,
Lovethedatabase.Wasabletomoodyittosuitmyneeds,buttheworkbookbloatedinto33MBfilesizeand
runsslow,anysuggestions?

Reply

102. nareshsays:
April28,2014at6:04am

PubliccnnAsNewADODB.Connection

Reply

103. Sakthisays:
April28,2014at11:24am

YoucanuseexcelasfrontendapplicationandaswellasDatabase.

Insertingnewrecords,updatingexistingnewrecordsanddataqueryasdonefromanapplicationisverywell
possibleinexcelwithvbaandsqlcombinedcommands.

IhavecreatedverygoodDataentryapplicationsusingexcelasfrontendanddatabase

Regards
Sakthi

Reply

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 40/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline

104. RodAyerssays:
May11,2014at2:34am

Iwonderifsomeonecouldhelpme.

IamusingSQLtoqueryanExceltabletoproduceanothertable.Everythingisfine,excepttherearetwo
columnsthathavedata,butwillalwaysbeemptyintheresultset.Oneofthecolumnsistext,theotherhas
avaluefromaDataValidationlist.Thereareseveralothercolumnswiththesecharacteristicsthatare
returnedjustfineintherecordset.

Anyhelpwouldbegreatlyappreciated.

Thankyou,
Rod

Reply

105. ConradoNatacsays:
May11,2014at5:27pm

Thisisaperfectexample.Iwilllookatthissample.Thanksforagoodwork.ThisiswhatIhavebeenlooking
for.

Reply

ajajsays:
May20,2014at11:07am

IkeepgettingtheerrorODBCdoesnotsupporttherequestedparameteserror2147217887atthe
lineexcel
rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic

Reply

106. ajajsays:
May20,2014at11:05am

IkeepgettingtheerrorODBCdoesnotsupporttherequestedparameteserror2147217887atline

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic

thefullcodeis

PrivateSubcmdReset_Click()
'clearthedata
cmbProducts.Clear
cmbCustomerType.Clear
cmbRegion.Clear
Sheets("View").Visible=True
Sheets("View").Select
Range("dataSet").Select
Range(Selection,Selection.End(xlDown)).ClearContents
EndSub

PrivateSubcmdShowData_Click()
'populatedata
strSQL="SELECT*FROM[data$]WHERE"
IfcmbProducts.Text""Then
strSQL=strSQL&"[Product]='"&cmbProducts.Text&"'"
EndIf

IfcmbRegion.Text""Then
IfcmbProducts.Text""Then
strSQL=strSQL&"AND[Region]='"&cmbRegion.Text&"'"
Else
strSQL=strSQL&"[Region]='"&cmbRegion.Text&"'"
EndIf
EndIf

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 41/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
IfcmbCustomerType.Text""Then
IfcmbProducts.Text""OrcmbRegion.Text""Then
strSQL=strSQL&"AND[CustomerType]='"&cmbCustomerType.Text&"'"
Else
strSQL=strSQL&"[CustomerType]='"&cmbCustomerType.Text&"'"
EndIf
EndIf

IfcmbProducts.Text""OrcmbRegion.Text""OrcmbCustomerType.Text""Then
'nowextractdata
closeRS

OpenDB

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Ifrs.RecordCount>0Then
Sheets("View").Visible=True
Sheets("View").Select
Range("dataSet").Select
Range(Selection,Selection.End(xlDown)).ClearContents

'Nowputtingthedataonthesheet
ActiveCell.CopyFromRecordsetrs
Else
MsgBox"Iwasnotabletofindanymatchingrecords.",vbExclamation+vbOKOnly
ExitSub
EndIf

'NowgettingthetotalsusingQuery
IfcmbProducts.Text""AndcmbRegion.Text""AndcmbCustomerType.Text""Then
strSQL="SELECTCount([data$].[CallID])AS[CountOfCallID],[data$].[Resolved]"&_
"FROM[Data$]WHERE((([Data$].[Product])='"&cmbProducts.Text&"')And"&_
"(([Data$].[Region])='"&cmbRegion.Text&"')And(([Data$].[CustomerType])='"&
cmbCustomerType.Text&"'))"&_
"GROUPBY[data$].[Resolved]"

closeRS
OpenDB

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Ifrs.RecordCount>0Then
Range("L6").CopyFromRecordsetrs
Else
Range("L6:M7").Clear
MsgBox"Therewassomeissuegettingthetotals.",vbExclamation+vbOKOnly
ExitSub
EndIf
EndIf
EndIf
EndSub

PrivateSubcmdUpdateDropDowns_Click()
strSQL="SelectDistinct[Product]From[data$]Orderby[Product]"
closeRS
OpenDB
cmbProducts.Clear

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
IfNotIsNull(rs.Fields(0))ThencmbProducts.AddItemrs.Fields(0)

rs.MoveNext
Loop
Else
MsgBox"IwasnotabletofindanyuniqueProducts.",vbCritical+vbOKOnly
ExitSub
EndIf

'
strSQL="SelectDistinct[Region]From[data$]Orderby[Region]"

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 42/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
closeRS
OpenDB
cmbRegion.Clear

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF

IfNotIsNull(rs.Fields(0))ThencmbRegion.AddItemrs.Fields(0)

rs.MoveNext
Loop
Else
MsgBox"IwasnotabletofindanyuniqueRegion(s).",vbCritical+vbOKOnly
ExitSub
EndIf
'
strSQL="SelectDistinct[CustomerType]From[data$]Orderby[CustomerType]"
closeRS
OpenDB
cmbCustomerType.Clear

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic
Ifrs.RecordCount>0Then
DoWhileNotrs.EOF
cmbCustomerType.AddItemrs.Fields(0)
rs.MoveNext
Loop
Else
MsgBox"IwasnotabletofindanyuniqueCustomerType(s).",vbCritical+vbOKOnly
ExitSub
EndIf
EndSub

Reply

107. JohnPaulsensays:
June13,2014at6:31am

Hello!IWonderifthereisaposibilitytomakethecomboboxesdependentofeachother.Ifyouchoosefrom
thecomboboxProducts,onlyRegionsrelatedtoProductswouldshowupinthecomboboxRegionsandsoon?

Reply

108. Jamessays:
June17,2014at7:07am

Hi!Ithinki'mwonderingaboutthesamethingasJohn.Isthereawayofmakingthedropdownboxes
dependentofeachother?Forinstance,whenichooseaRegioninthedropDown,onlyProductsrelatedto
thatregionwillshowintheProductsdropDown.Ifanybodyhadanyideasonhowtodothis,pleaseshare.

Bestregards,avbanovice

Reply

109. LisaPereirasays:
June25,2014at2:48pm

Hi,

thisisawesome,ilovethissite..lotsofinformation..mineisaverysimplequestion,itsprobablyanswered,
butIcannotfindadirectresource..
IuseExcelasaDBbycreatingquery'swithADOvbaandpullingfromtheDbase.
iamprettynewtoaccessbutfamiliarwithEXCELvba..
isthereawayicanusethesamequery'sandtransferthedatatoanewdatabaseiwanttocreateinACESS.
howdoigoaboutit?cansomeoneadviseorforwardsomewhereicanreferthis?

Reply

110. Saketsays:

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 43/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
July17,2014at4:38pm

Ihaveacolumninexcelwithvaluesasnumberaswellasstring.TheSQLqueryissomehownotfetchingall
thedistinctrecords..Canyouhelp?
SelectDistinct[Model]From[QueryData$]WHERE[Model]ISNOTNULLOrderby[Model]

Thanks,

Reply

111. Cruisersays:
October17,2014at9:12pm

ThanksVijay!IalsowanttouseExcelasadatabaseforuserswhodonothaveaseparatedatabaseprogram
availabletothem.Canyoupleasereadthefollowingscenarioandgivemeyourthoughts?Iwanttowritea
COMAddInwhichwillbeinstalledoneachuser'smachineandisusedtoreadfromandwritetothesingle
databaseworkbook(whichresidesontheserver).Theaddinwillcontainauserform.Whentheuserformis
filledout,Iclickthe"Add"buttonwhichinvokesthecodetocopytheuserformdata,activatethedatabase,
addtherecordtothedatabase,updatemyworkbookfromthedatabase(addingmynewrecordandallother
changessinceIlastupdatedmyworkbook),andclosethedatabase.Itshouldonlytakeafewseconds,but
whathappensiftwoormoreuserstrytoaddarecordatthesametime?Sharingisnotanoption.Canmy
addincontainacontingencythattellsit"ifthedatabaseworkbookisbeingaccessedbyanotheruser,stop
theprocessbutkeeptryingtoaccessituntilitbecomesavailable,thenopenitandcontinuetheprocess"?
MaybereplacethemessageboxDatabase.xlsxislockedforeditingbyanotheruserwithUpdating
Database?Inmyscenario,thedatabaseworkbookistheonlyelementontheserver.Itwillonlybeusedfor
datastorageandretrieval,withtheresultsbeingdisplayedandmanipulatedineachuser'spersonalversionof
theworkbook(residingontheirownmachine).Isthisdoable?

Reply

Cruisersays:
November5,2014at9:21pm

IguessI'mtheonlyone.Well,inthefuture,ifanyoneelseistryingtocreateanexcel"database"ona
shareddrive,checkouthttp://www.cpearson.com/excel/WaitForFileClose.htm
Ifsomeoneelseisaccessingyour"database"ontheshareddrive,thiscodekeepscheckinguntilthe
filetoclosed,thenopensit,addsorretrievesdata,savesandclosesit.Ifounditveryhelpful.

Reply

Cruisersays:
November5,2014at9:24pm

"...thiscodekeepscheckinguntilthefileISclosed..."

Reply

112. ConradoNatacsays:
November3,2014at4:46am

HelloVijay,

icantgetthislineofcodetowork.

Ilovethisarticlethatyouwroteandamtestingit.

OptionExplicit
PubliccnnAsNewADODB.Connection
PublicrsAsNewADODB.Recordset
PublicstrSQLAsString

PublicSubOpenDB()
Ifcnn.State=adStateOpenThencnn.Close
cnn.ConnectionString="Driver={MicrosoftExcelDriver(*.xls,*.xlsx,*.xlsm,*.xlsb)}DBQ="&_
ActiveWorkbook.Path&Application.PathSeparator&ActiveWorkbook.Name
cnn.Open
EndSub

PublicSubcloseRS()

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 44/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Ifrs.State=adStateOpenThenrs.Close
rs.CursorLocation=adUseClient

EndSub

PrivateSubcmbtest_Click()

xcustno=Sheets("View").Range("O14").Value

closeRS
OpenDB

strSQL="SELECT*FROM([data$]WHERE[data$].[Cust#]).value=xcustno"

closeRS

'thisistheconnrection
OpenDB

rs.OpenstrSQL,cnn,adOpenKeyset,adLockOptimistic

'disposetheconnection
Setcnn=Nothing

Ifrs.RecordCount>0Then
Sheets("View").Visible=True
Sheets("View").Select
Range("dataSet").Select
Range(Selection,Selection.End(xlDown)).ClearContents

'Nowputtingthedataonthesheet
ActiveCell.CopyFromRecordsetrs

EndIf

'disposetherecordeset
Setrs=Nothing

EndSub

Reply

113. Rajeshsays:
January6,2015at11:28pm

Iamcopying28000rowswith8columnsusingcopyfromrecordsetoption.Butitistakinglotoftimetocopy
thedataintoexcelmorethan1hour.Iamnotsurewhythisisrunningforthismuchtime.Anyonehave
anyidea

Reply

AndrePoormansays:
January27,2015at3:19am

Vijay,

IamusingExcelasadatabaseasyouexcellentlyshow,butIamalsotryingtousetemporarytables
withintheSQLcode.Igetanerror.OnesuggestionIgotwastoput"SETNOCOUNTON"and"SET
NOCOUNTOFF"intheSQLstatementbutInowgettheerror:

'Runtimeerror'2147217900(80040e14)':
'[Microsoft][ODBCExcelDriver]InvalidSQLstatementexpected'DELETE','INSERT','PROCEDURE',
'WELECT',or'UPDATE'

Anythoughts?

Reply

114. Stephensays:
January28,2015at11:27am

AsimplewayistousethepowerfulinherentfeatureofExcel
AdvancedFilter.Ihaveoutlinedabasicsetofvbacodebelowthatcanbeusedtoqueryanexcellist/
http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 45/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
database.YouhavetosetupacriteriarangeonyourspreadsheetanddefineYourRange(exceldatabase)and
YourCriteria(querycriteria).

SubFilter()
DimListasRange
DimCriteriaasrange
SetList=Range(YourRange)
SetCriteria=Range(YourCriteria)
WithList
.AdvancedFilterAction:=xlFilterInPlace,CriteriaRange:=Criteria,Unique:=False
EndWith
EndSub

Reply

115. Hasansays:
February22,2015at8:03pm

ThanksVijayforsharing,greatstuff.

FewyearsagoIhadtocreateaportfolioselectioninterface,emulatingExcelautofilter.IusedAdvanced
Filterswithsomecode,butitwasnotaselegantasthis(onesheetperdropdown+onecontrolsheet).

Itwouldbenicetohave"communicating"dropdownsplusthe(Selectall)possibility(asinAutoFilter)

Reply

116. srinivassays:
May14,2015at7:04pm

Hi,Ihaveonedoubtinaboveexample.Iftherecordsinwhichthesqlqueryisfetchingishavingspecial
characters,thenwhatwouldbetheoutput.
Forexample,
ihave10recordsinthedatabasesheetlikeabd's,aws'q,xza',qaws,tc....likethat1015records.
So,Myquestionishowtofetchtheserecordsifigivesamevalue(forex:abd's)indropdowncontrol.
Evenifwetryusingregex/wildcardcharactersonerecordwillnotbedisplayed.
Trythisandhelpmeoutguys........
ThanksinAdvance.

Reply

Andrewsays:
September18,2016at7:46pm

Ihadthesameproblem.FirstIusedadataconnectioninExceltoruntheSQLbutfoundcompatibility
issueswithExcel2010.
IamnowbacktouseADO(DB)butchangedtheconnectionstringto:
"Provider=Microsoft.ACE.OLEDB.12.0"&_
"ExtendedProperties='Excel8.0'"&_
"DataSource="&ThisWorkbook.FullName&""
ThisdoesrequireACEtobeavailable.
AlternativelyJETcanbeusedinsteadofACEbutthiscannothandleasmuchdata.

Reply

117. yothinsays:
June5,2015at3:27am

ifIaddpictureineachdata(hyperlinkorcomment),howtoshowthatdatawithpicture??

Reply

118. Mikesays:
July1,2015at7:13am

WhereIworkthegovernmentwillnotallowustouseMSAccessduetosomesecurityreasons.Wehavehad
ouronlyotherdatabasesoftwareavailableforustousewithoutpayingadeveloperremoved...Iwon'tgointo
thereasonasitupsetsme.

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 46/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Anyway,wehaveoperatorlogsthatarenowfilledoutonaWorddocument,andthentheysaveeach
individualdocument.Wellwith3shiftsadaythisisalotofdocumentsandifyouwanttogobackthrough
themtofindsomething,ortrenddatayouhavealotof$&!+tosortthrough....SO,Ihavemadethe
documentsavethedatainanExcelworkbookusingADODBinVBA.Thenthedataisinaspreadsheetforus
toqueryandtrendtoourheartsdelight.IfiwanttogobacktoseeaparticularlogIcanthenretrievethe
desireddataandpopulatetheWorddocument.

Nothisisnotideal,butisaworkaroundasittakesthisplaceyearstogetaroundtogivingusnewsoftware,
orwehavetopayathirdpartydeveloperaloadofmoney.

TheonlyissueIhaveisinthecommentfields.Therecordsetfieldswon'tallowformorethan255characters.
I'vetriedchangingthedatatypeusingtheALTERTABLEmethod,butnoluck...sofar.

Anyway,IamforthemostpartsuccessfullyusingExcelasadatabase,andonceIsortouthowtodealwith
therichtexttypefieldswithmorethan255charactersitwillbegoodenough.

Reply

119. Alsays:
August11,2015at7:44pm

HiChandoo,

Thanksforyourexcellentpost.Justaquestion:Iamworkingonexactlysamethingwiththeexceptionof
usingtextboxinsteadofdropdownboxes.AdditionallyIwouldliketohaveseparateworksheetforadding
dataintothedb.Intotalitwouldhavethreeworksheetasdata,add,view.

Couldyouhelpmeforusingtextboxes?

Thanksalot,

Reply

120. DeekshaBalujasays:
March18,2016at1:51pm

DearChandoo,

I'mverymuchnaiveatthetechniqueifusingExcelasyourdatabase,Isawthevbacodeafterdownloading
thesamplefile,couldyoupleasepleasetellmewherehavethecommands[data$]andproducthavecome
fromandhowhaveyoudesignedcomboboxesinthiscase.

Thanksalotinadvance

Reply

121. Helmasays:
April19,2016at1:30pm

Hi.I'musingExcelasadatabaseandpopulatetherecordsinamulticolomnlistboxinauserforminWord
vba.Imanagedtodothis.
Icanevensortthedifferentcolumnsinthelistbox.
ButnowIwanttofillthetextboxesintheuserformwiththevaluesoftheselectedlistboxitem.Thefirst
columnhasanIDno.
CananyonetellmehowtodothatoristhisatypicalWordquestion?
ThenI'msorryI'veputthequestionhere.
Thankyou.

Helma

Reply

122. MadhuDNsays:
June20,2016at11:57am

DearAll,

I'mlookingforVBAcodefordataimportfromwebsitetoexcel!!
Requirement:ihavecompanywebsitewhichweneedtodownloaddataeverytime,needcodeforlogin
websitebycredentialsanddownloadadataautomaticallybyusingVBAcode.

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 47/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Thanksforyoursupport!
MadhuDN(HR)

Reply

123. JoseLobosays:
June20,2016at4:15pm

Hi,Madhu,
Iwouldsuggestyoutosearchtheweb.Therearemanywebsitesaboutthat.Takealookat:
http://www.wiseowl.co.uk/blog/s393/scrapingwebsitesvba.htm
Ihaveasimilarproblemtogetatablefromawebsitethatrequirestwodatesandaclick,butIdidnotsolve
theproblemyet.

Reply

124. JoseLobosays:
June20,2016at4:21pm

Hi,Madhu,

Again,youcangetwebdatadirectlyfromexcel(withoutVBACode).

Seethelinkformoreinformation:

http://www.howtogeek.com/howto/24285/useonlinedatainexcel2010spreadsheets/

Reply

125. Martinsays:
July11,2016at3:08pm

VBAbeginnerhereHowwerethedropdownlistsandbuttonscreatedinthisdatabasetemplate?I'mhaving
troublefiguringthemoutastherearenouserformsshownintheVBAeditor?Anyhelpwouldbeappreicated.

Reply

126. PinderSinghsays:
July24,2016at11:53pm

idonotknowNothingaboutVBAbutstillbuildthisuserformretrievedatafromoneworksheettoaddedinto
theotherworksheetithinktheirgottabeabetterwaytodothisifyoucouldhelpidonotknowwhereto
Uoloadmyworkbooksopleaseletmeknow

Reply

127. Rensays:
July26,2016at7:12am

asyouareextractingdatafromthesheetIwantittobefromadatabase.Howisthatpossible?

Reply

128. Normansays:
September25,2016at3:17pm

Sadly,thisnolongerworksonOffice2016(HomeandStudent).Iranyourexamplefilewithoutchanging
anything,andkeepgetting"microsoftexceliswaitingforanotherapplicationtocompleteanoleaction".Do
youhaveasolutiontothis?Wouldreallyappreciateifyoucouldhelp.Thanks.

Reply

Hui...says:
September26,2016at2:35am

@Norman

ItsuredoesworkinExcel2016
DidyouaddthereferencetotheActiveXdataLibrary?

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 48/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
Didyousavethefiletoalocaldrive?
DidyouclickonUpdateDropDowns?(Thisisimportant)

Ifitstilldoesn'tworkcanyoutelluswhatversionofExcelandWindowsyouareusing?

Reply

Normansays:
September26,2016at5:01am

Itdoesn'tforme.I'veuploadedafewscreenshotstoanalbumhere:http://imgur.com/a/eDU6H

AreferencetotheActiveXDataLibraryexists(asshowinthescreenshot).

Thefileissavedtoalocaldirve.

TheerroroccursafterIclickonthe"UpdateDropDowns"Button(includedinthescreenshot
album)

OnethingI'venoticed,isthattheMicrosoftActiveXDataObjects6.0Libraryreferencesa
"msado60.dll"intheexample,whereas,it'sa"msado60.tlb"fileinExcel2016(whichIuse).

Couldthisdifferencebecausingtheerror?

Reply

129. shahbazNawazsays:
October2,2016at9:05am

DearVijay&Garouda,

Dearboththanksalottoproducedthisarticalbutihaveoneproblemineedonlyspecificrangefrom"data"
toshowinviewtabidontwanttoshowall.

Canyoupleasehelpme.

Regards,

ShahbazNawaz

Reply

130. Collinsays:
November22,2016at2:06am

Itriedthisandamgettinga(runtimeerror)thebelowerroronline

Ifrs.RecordCount>0Then
Sheets("View").Visible=True
Sheets("View").Select
Range("dataSet").Select(thisline)
Range(Selection,Selection.End(xlDown)).ClearContents

Notsurewhereitwentwrongandanyhelpwillbemuchappreciated

Itshowsthiserror
Runtimeerror'1004'
method'Range'ofobject'_Worksheet'failed

Cheers

Collin

Reply

Hui...says:
November22,2016at3:33am

@Collin

IsthereaNamedRangecalleddataSetalreadysetupontheworksheet?

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 49/50
12/29/2016 UsingExcelAsYourDatabase|Chandoo.orgLearnMicrosoftExcelOnline
I'drecommendaskingthisintheChandoo.orgForums
http://forum.chandoo.org/

Attachasamplefilewithsomedataifyoucan

Reply

LeaveaReply


ComprehensiveGuidetoVLOOKUP&Other SignupformyExcelDashboardMasterclassin
LookupFormulas Australia

http://chandoo.org/wp/2012/04/02/usingexcelasyourdatabase/ 50/50

You might also like