Tải bản đầy đủ - 0 (trang)
Chapter 12. Loading and Manipulating Data

Chapter 12. Loading and Manipulating Data

Tải bản đầy đủ - 0trang

andDAO.Recordset.



Codeusedinthischapterandadditionalsamplesareavailablein

ch12.xls.







12.1.WorkingwithQueryTableObjects

TheQueryTableobjectgivesyouprogrammaticaccesstothe

databasequeriesthatarenativetoExcel.Thesedatabase

queriesletyouretrievedatafromavarietyofdatasourcesand

insertthedataintoyourworksheets.IntheExcelinterface,you

createadatabasequerybyclickingImportExternalData,New

DatabaseQueryontheDatamenu.

Incode,youcreateadatabasequerybyaddingaQueryTable

objecttotheQueryTablescollection.Whenyoudothis,yousupply

aconnectionstringtoyourdatasourceaswellasadestination

onyourworksheetwhereyouwanttheresultsofthequeryto

beinserted.Forexample,thefollowingcodeinsertsinformation

foraspecificproductfromtheProductstableoftheNorthwind

Traderssampledatabaseintothecurrentworksheet,starting

withthefirstcelloftheworksheet:



DimstrConnAsString

DimstrSQLAsString

DimqtAsQueryTable



strConn="ODBC;DSN=MSAccessDatabase;"&_

"DBQ=C:\ProgramFiles\MicrosoftOffice\OFFICE11\SAMPLES\Nor



Setqt=ActiveSheet.QueryTables.Add(Connection:=strConn,_

Destination:=ActiveSheet.Range("A1"))

qt.CommandText="SELECT*FROMProductsWHERE(Products.Produc

qt.Refresh



YoucanalsousetheADOorDAOprogramminginterfacesto

createarecordset,andusetheresultingRecordsetobjectasyour

datasource.Touseeitheroftheseprogramminginterfacesin

Excel,youneedtoaddareferencetotheappropriateobject



library.OntheToolsmenuintheVBAprogramming

environment,selectReferences,thenselecttheappropriate

objectlibraryfromthelist.Forexample,thefollowingcode

createsaquerytableusingtheEmployeestableinthe

NorthwindTraderssampledatabaseandinsertstherecordset

nameanddataintheactiveworksheet:

DimstrDbPathAsString

DimdbAsDAO.Database

DimrsAsDAO.Recordset

DimqtAsQueryTable



strDbPath="C:\ProgramFiles\MicrosoftOffice\"&_

"OFFICE11\SAMPLES\Northwind.mdb"



Setdb=OpenDatabase(strDbPath)

Setrs=db.OpenRecordset("Employees")



Setqt=ActiveSheet.QueryTables.Add(Connection:=rs,_

Destination:=ActiveSheet.Range("A3"))



ActiveSheet.Range("A1")=qt.Recordset.Name&"table:"



qt.Refresh



TheADOandDAOprogramminginterfacesarediscussedlater

inthischapter.



12.2.QueryTableandQueryTablesMembers

UsetheQueryTablescollectiontocreatenewquerytablesandadd

themtoaworksheet.UsetheWorksheetobject'sQuertyTables

propertytogetareferencetothiscollection.UsetheQueryTable

objecttorefreshthedatainthequerytableandtocontrol

otheraspectsofthequery.TheQueryTablesandQueryTableobjects

havethefollowingmembers.Keymembers(showninbold)

arecoveredinthefollowingreferencesection:



WebquerymembersarecoveredinChapter24.



Add1



AdjustColumnWidth



AfterRefresh



Application2



BackgroundQuery



BeforeRefresh



CancelRefresh



CommandText



CommandType



Connection



Count1



Creator2



Delete



Destination



EditWebPage



EnableEditing



EnableRefresh



FetchedRowOverflow



FieldNames



FillAdjacentFormulas



Item1



ListObject



MaintainConnection



Name



Parameters



Parent2



PostText



PreserveColumnInfo



PreserveFormatting



QueryType



Recordset



Refresh



Refreshing



RefreshOnFileOpen



RefreshPeriod



RefreshStyle



ResetTimer



ResultRange



RobustConnect



RowNumbers



SaveAsODC



SaveData



SavePassword



SourceConnectionFile



SourceDataFile



TextFileColumnDataTypes



TextFileCommaDelimiter



TextFileConsecutiveDelimiter



TextFileDecimalSeparator



TextFileFixedColumnWidths



TextFileOtherDelimiter



TextFileParseType



TextFilePlatform



TextFilePromptOnRefresh



TextFileSemicolonDelimiter



TextFileSpaceDelimiter



TextFileStartRow



TextFileTabDelimiter



TextFileTextQualifier



TextFileThousandsSeparator



TextFileTrailingMinusNumbers



TextFileVisualLayout



WebConsecutiveDelimitersAsOne



WebDisableDateRecognition



WebDisableRedirections



WebFormatting



WebPreFormattedTextToColumns



WebSelectionType



WebSingleBlockTextImport



WebTables



1Collectiononly

2Objectandcollection



querytables.Add(Connection,Destination,[Sql])



Createsanewquerytableandaddsittotheworksheet.

ReturnsaQueryTableobject.

Argument Description

Connection



Astringorobjectreferenceidentifyingthesourceofthedata.



Destination



ARangeobjectidentifyingtheupper-lefthandcornerofthedestinationofthe

querytable.



Sql



IftheConnectionargumentisanODBCdatasource,thisargumentisastring

containingtheSQLquerytoperform.Otherwise,includingthisargumenteither

causesanerrororisignored.



querytable.AdjustColumnWidth[=setting]



SetthispropertytoFalsetodisabletheautomaticadjustment

forthebestfitforcolumnsinthespecifiedquerytable.

querytable.BackgroundQuery[=setting]



Truerefreshesdatainthequerytableasynchronously.False

refreshesdatasynchronously.DefaultisTrue.

TheBeforeRefreshandAfterRefresheventsoccurwhetherornot

thequeryisrefreshedsynchronouslyorasynchronously.When

synchronous,botheventsoccurbeforetheRefreshmethod

completes.Whenasynchronous,onlytheBeforeRefreshevent

occursbeforetheRefreshmethodcompletes,thenprogramflow

continues.

querytable.CancelRefresh



Cancelsanasynchronousquery.Youcan'trefreshordeletea

querywhilethatqueryhasrefreshpending.Whenworkingwith

asynchronousqueries,youshouldcheckthequerytable's

Refreshingpropertyand(possibly)cancelthependingrefresh

beforedeletingorrefreshingthatqueryagain.

Thefollowingcodecancelsanypendingrefreshesbefore

refreshingaquery:

Ifqt.RefreshingThenqt.CancelRefresh

qt.Refresh



querytable.CommandText[=setting]



Setsorreturnsthecommandstringforthespecifiedquery

table.Thefollowingcodereturnstheresultsofaquerywiththe

specifiedcommandstring:



DimstrConnAsString

DimstrSQLAsString

DimqtAsQueryTable



strConn="ODBC;DSN=MSAccessDatabase;"&_

"DBQ=C:\ProgramFiles\MicrosoftOffice\OFFICE11\SAMPLES\Nor

Setqt=ActiveSheet.QueryTables.Add(Connection:=strConn,_

Destination:=ActiveSheet.Range("A1"))



qt.CommandText="SELECT*FROMProductsWHERE(Products.Produc

qt.Refresh



querytable.CommandType[=setting]



Setsorreturnsthetypeofcommandstringusedbythe

specifiedquerytable.ThetypecanbexlCmdSQL,aSQLstring

(default);xlCmdCub,acubenameforanonlineanalytical

processing(OLAP)datasource;xlCmdDefault,commandtextthat

theOLEDBproviderunderstands;orxlCmdTable,atablename

foraccessingOLEDBdatasources.

querytable.Connection[=setting]



Setsorreturnstheconnectionstringforthespecifiedquery

table.Thefollowingcodecreatesaquerytable,returnsits

results,anddisplaystheconnectionstringincellA6:



DimstrConnAsString

DimstrSQLAsString

DimqtAsQueryTable



strConn="ODBC;DSN=MSAccessDatabase;"&_

"DBQ=C:\ProgramFiles\MicrosoftOffice\OFFICE11\SAMPLES\Nor



Setqt=ActiveSheet.QueryTables.Add(Connection:=strConn,_

Destination:=ActiveSheet.Range("A1"))

qt.CommandText="SELECT*FROMProductsWHERE(Products.Produc

qt.Refresh

ActiveSheet.Range("A6")=qt.Connection



querytable.Delete



Deletesaquerytable.Ifthequerytableisrefreshing

asynchronously,Deletecausesanerror.Deletingaquerytable

doesnotremovedatafromcellsonaworksheetitjustremoves

theabilitytorefreshthosecellsfromtheirdatasource.

Thefollowingcodedeletesallofthequerytablesontheactive

worksheetandclearstheirdata:

DimqtAsQueryTable

ForEachqtInActiveSheet.QueryTables

Ifqt.RefreshingThenqt.CancelRefresh

qt.Delete

Next

ActiveSheet.UsedRange.Clear



querytable.Destination



ReturnsaRangeobjectcontainingthecellintheupper-lefthand

cornerofthequerytable.

Thefollowingcodeselectsthefirstcellofaquerytableonthe

activeworksheetandasksiftheuserwantstodeleteit:

ForEachqtInActiveSheet.QueryTables

qt.Destination.Select

IfMsgBox("Deletequerytable?",vbYesNo)=vbYesThen

Ifqt.RefreshingThenqt.CancelRefresh

qt.ResultRange.Clear

qt.Delete

EndIf

Next



querytable.EnableEditing[=setting]



Trueallowstheusertochangethequerydefinitionthroughthe

Datamenu'sImportExternalDatasubmenu.Falsedisablesthe

ImportExternalDatamenuitems.DefaultisTrue.

querytable.EnableRefresh[=setting]



TrueallowstheusertorefreshthequerythroughtheData

menu'sRefreshDataitem.FalsedisablestheRefreshData

menuitem.DefaultisTrue.

querytable.FetchedRowOverflow[=setting]



Trueifthenumberofrowsreturnedbythelastrefreshofthe

specifiedquerytableisgreaterthantheavailablenumberof

rows.



querytable.FieldNames[=setting]



Trueiffieldnamesfromthedatasourcearedisplayedas

columnheadingsforthereturneddata.Thefollowingcode

specifiesthatfieldnameswillnotbedisplayedinthequery

table:

ActiveSheet.QueryTables(1).FieldNames=False



querytable.FillAdjacentFormulas[=setting]



Truecausescalculatedcellstotherightofthequerytabletobe

repeatedforeachrowwhenthequerytableisrefreshed.False

doesnotrepeatadjacentformulas.DefaultisFalse.

SetFillAdjacentFormulastoTrueinordertocreaterowtotals,or

othercalculations,foreachrowinthequerytable

automatically.Tousethisfeature,createaquerytable,adda

formulaforthefirstrowinthequerytable,set

FillAdjacentFormulastoTrue,thenrefreshthedata.Formore

information,seeChapter24.

querytable.MaintainConnection[=setting]



ThispropertyreturnsTrueiftheconnectiontothespecified

querytable'sdatasourceismaintainedafterarefresh

operation.YoucansetthispropertyforqueriestoOLEDB

sourcesonly.

querytable.Parameters



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 12. Loading and Manipulating Data

Tải bản đầy đủ ngay(0 tr)

×