Tải bản đầy đủ - 0 (trang)
Chapter 24. Getting Data from the Web

Chapter 24. Getting Data from the Web

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

Thischapterdescribeshowtousewebqueriesandwebservices

toretrievedatafromtheWebandimportitintoExcel.The

samplesinthischapterdemonstrateavarietyofprogramming

taskswiththesetwoapproaches,includingpassingparameters,

formattingresults,gettingdataasynchronously,anddisplaying

resultsthroughXMLmaps.



Codeusedinthischapterandadditionalsamplesareavailablein

ch24.xls.



24.1.PerformWebQueries

Webqueriesareaquickwaytoimportdatafromawebpage

intoaworksheetusingaQueryTableobject.Toperformaweb

query:

1. FromtheDatamenu,chooseImportExternalData,then

chooseNewWebQuery.ExceldisplaystheEditWebQuery

dialogshowninFigure24-1.



Figure24-1.Usewebqueriestoimportdata

directlyfromawebpage



2. Typetheaddressofthewebpageyouwanttoimportdata

fromintheAddressbarandclickGotonavigatetothat

page.Itisusuallyeasiesttofindthepageyouwantinyour



browser,thencutandpastethataddressintotheEditWeb

Querydialogbox.

3. Excelplacessmallyellowboxesnexttotheitemsyoucan

importfromthepage.Clickontheitemoritemsyouwant

toimportandExcelchangestheyellowboxtoagreen

checkmark.

4. ClicktheOptionsbuttontosethowExcelformatsimported

items.FormattingoptionsareshowninFigure24-2.

5. ClosetheOptionsdialogboxandclickImport.Excel

displaystheImportDatadialogboxshowninFigure24-3.



Figure24-2.Setformattingoptionsforthequery



Figure24-3.Choosethedestinationforthe

importeddata



6. ClickPropertiestodeterminehowthequeryisperformed,

suchashowthedataisrefreshed.Figure24-4showsthe

querypropertysettings.

7. ClosethePropertiesdialogandclickOKtoimportthedata.

Figure24-5showsareal-timestockquoteandquotehistory

importedfromtheYahoo!website.Yahoo!isagoodsourcefor

thistypeofwebquerybecauseitisafreeserviceanddoesn't

requireyoutoregisterorsignin.

Ifyourecordtheprecedingwebquery,you'llgetcodethat

lookssomethinglikethis:



WithActiveSheet.QueryTables.Add(Connection:=_

"URL;http://finance.yahoo.com/q/ecn?s=SNDK",Destination:=R

.Name="Real-TimeQuote"

.FieldNames=True

.RowNumbers=False

.FillAdjacentFormulas=False

.PreserveFormatting=True

.RefreshOnFileOpen=False

.BackgroundQuery=True

.RefreshStyle=xlOverwriteCells

.SavePassword=False

.SaveData=True

.AdjustColumnWidth=True

.RefreshPeriod=0



.WebSelectionType=xlSpecifiedTables

.WebFormatting=xlWebFormattingNone

.WebTables="22"

.WebPreFormattedTextToColumns=True

.WebConsecutiveDelimitersAsOne=True

.WebSingleBlockTextImport=False

.WebDisableDateRecognition=False

.WebDisableRedirections=False

.RefreshBackgroundQuery:=False

EndWith



WithActiveSheet.QueryTables.Add(Connection:=_

"URL;http://finance.yahoo.com/q/hp?a=01&b=5&c=2003&d=01&e=5&f

,Destination:=Range("A9"))

.Name="PriceHistory"

.FieldNames=True

.RowNumbers=False

.FillAdjacentFormulas=False

.PreserveFormatting=True

.RefreshOnFileOpen=False

.BackgroundQuery=True

.RefreshStyle=xlOverwriteCells

.SavePassword=False

.SaveData=True

.AdjustColumnWidth=True

.RefreshPeriod=0

.WebSelectionType=xlSpecifiedTables

.WebFormatting=xlWebFormattingNone

.WebTables="30"

.WebPreFormattedTextToColumns=True

.WebConsecutiveDelimitersAsOne=True

.WebSingleBlockTextImport=False

.WebDisableDateRecognition=False

.WebDisableRedirections=False

.RefreshBackgroundQuery:=False

EndWith



Figure24-4.UsethePropertiespagetonamethe

query,sethowdataisrefreshed,andsethow

cellsareinserted



Figure24-5.Usingawebquerytogetstockprice

data



Somekeypropertiesandmethodsshowninboldinthe

precedingsamplebearmentionhere:

TheAddmethodcreatesthequeryandaddsittothe

worksheet.

TheRefreshStylepropertytellsExceltooverwriteexisting

dataratherthantoinsertnewcellseachtimethequeryis

refreshed.

TheWebTablespropertyidentifieswhichitemfromthepageto

import.Excelassignsanindextoeachitemonthepage,

andyoucanimportoneormoreitemsortheentirepageif

WebSelectionTypeissettoxlEntirePage.

TheRefreshmethodimportsthedataontotheworksheet.

Withoutthismethod,thequeryresultsarenotdisplayed.



ThequeryitselfconsistsoftheConnection,WebTables,and

formattingproperties.Ifyousavethewebquerytoaqueryfile

(.iqy),thedatalookslikethis:



WEB

1

http://finance.yahoo.com/q/hp?a=01&b=5&c=2003&d=01&e=5&f=20



Selection=30

Formatting=None

PreFormattedTextToColumns=True

ConsecutiveDelimitersAsOne=True

SingleBlockTextImport=False

DisableDateRecognition=False

DisableRedirections=False



WhenExcelupdatesawebquery,asmall,greenglobeis

displayedinthestatusbaratthebottomofthescreen,as

showninFigure24-6.Thissymbolindicatesthatthequeryis

beingrefreshedfromtheInternet.



Figure24-6.Excelisrefreshingthequeryfrom

theInternet



24.1.1.ModifyaWebQuery

Youcanmodifyawebquerybyright-clickingonthequeryand

selectingEditQuery.Inmanycases,however,you'llwanta



moreautomatedapproach.Forexample,youmaywanttolet

theuserchangethestocksymbolintheprevioussample.Todo

that,usecodeto:

1. ChangetheConnectionpropertyofthequery.

2. Refreshthequery.

Forexample,thefollowingcodeallowstheusertoenterastock

symbolinanamedrangeontheworksheettogetcurrentand

historicalpricedataforthatstock:



DimwsAsWorksheet,qtAsQueryTable

Setws=ThisWorkbook.Sheets("WebQuery")

Setqt=ws.QueryTables("Real-TimeQuote")

qt.Connection="URL;http://finance.yahoo.com/q/ecn?s="&_

ws.Range("Symbol").Value

qt.Refresh

Setqt=ws.QueryTables("PriceHistory")

qt.Connection=

"URL;http://finance.yahoo.com/q/hp?a=01&b=5&c=2003&d=01&e=5

_ws.[Symbol].Value

qt.Refresh



Ifyouruntheprecedingcode,youmaynoticethatthequeryis

notupdatedrightaway.Bydefault,webqueriesaredoneinthe

backgroundasynchronously.ThisavoidstyingupExcelwhile

thewebsiterespondstothequery,butitcancauseanerrorif

yourefreshthequeryagainbeforethefirstrequesthashada

chancetorespond.Youcanavoidthisbynotperformingthe

queryinthebackground.Forexample,thefollowingcodeturns

offasynchronousqueries,waitingforaresponsebefore

executingthenextline:

qt.BackgroundQuery=False

qt.Refresh



or,moresimply:

qt.RefreshFalse



ThiscausesExceltowaitwhilethequerycompletes.Duringthis

time,theusercan'teditcellsorperformothertasks.Ifthisis

toomuchofaburden,usetheQueryTableobject'sRefreshing

propertytoavoidasynchronouscollisions:



Setqt=ws.QueryTables("Real-TimeQuote")

IfNotqt.RefreshingThen

qt.Connection="URL;http://finance.yahoo.com/q/ecn?s="

ws.[Symbol].Value

qt.Refresh

Else

MsgBox"Similarqueryispending,pleasewaitasecond

EndIf



Theprecedingcodecheckswhetherthewebqueryisalready

executingbeforecallingRefresh.Ifapreviousqueryisstill

executing,theuseristoldtotryagainlater.Noticethatthis

codechecksthestatusofaqueryperformedbyasinglequery

table.Other,differentquerytablesmayhavependingresults

withoutcausingacollisionyouneedtochecktheRefreshing

propertyofonlythetargetquerytablebeforeattemptingto

changeorrefreshaquery.



24.1.2.PerformPeriodicUpdates

Ifthedatainawebquerychangesfrequently,youmaywantto



haveExcelautomaticallyupdatetheinformationperiodically.

Sincewebqueriesalreadyrunasynchronouslyinthe

background,gettingthemtoupdateperiodicallyisasimple

matterofsettingaproperty:

Setqt=ws.QueryTables("Real-TimeQuote")

qt.RefreshPeriod=1



Now,thequerywillupdateeveryminute.Toturnoffthe

backgroundquery,settheRefreshPeriodto0asshownhere:

qt.RefreshPeriod=0



Interestingly,theBackgroundQuerypropertycanbeFalseandyou

canstillperformperiodicqueries.Inthatcase,theExceluser

interfacepausesperiodicallywheneverthequeryisbeing

refreshed.



24.1.3.TrapQueryTableEvents

Performingwebqueriesinthebackgroundcanseemalittle

strangeparticularlyiftheyaresettorefreshperiodically.Most

Excelactionsaresynchronous,anditmightsurpriseauserto

seeExcelpauseforasecond,updatesomecells,andthen

continueonasifnothinghappened.Thiscanbecomeabig

problemifthesourceofthewebquerychangesandcausesthe

webquerytofailtheuserwillseeanerrormessageperiodically

andmaynotknowwhattodoorhowtofixit(Figure24-7).



Figure24-7.Failedwebqueriesmaydisplay

errorsasynchronously



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

Chapter 24. Getting Data from the Web

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

×