Tải bản đầy đủ - 0 (trang)
Chapter 9. Working with Worksheets and Ranges

Chapter 9. Working with Worksheets and Ranges

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

Formatandchangetext

Workwithscenarios

Thischapterincludestask-orientedreferenceinformationfor

thefollowingobjectsandtheirrelatedcollections:Worksheet,

Outline,Range,andScenario.



Codeusedinthischapterandadditionalsamplesareavailablein

ch09.xls.



9.1.WorkwithWorksheetObjects

WorksheetsaretheworkhorsesofExcel.Mostofthetimewhen

youprogramExcel,youaredoingsomethingwithaworksheet,

eitherwiththeactivesheetorsomeothersheetthatyou

specify.UsetheWorksheetscollectiontocreatenewworksheetsor

torefertoaspecificworksheet.Forexample,tocreateanew,

emptyworksheetinExcel,usetheAddmethodontheSheetsor

Worksheetscollection:

Dimws1AsWorksheet

Dimws2AsSheet



Setws1=Worksheets.Add

Setws2=Sheets.Add



Onceyou'vedeclaredaworksheetvariableandassignedita

referencetoaWorksheetobject,asinthepreviouscodefor

creatinganewworksheet,youcanusethevariabletoreferto

theworksheet'spropertiesandmethods.Youcanalsousethe

ActiveSheetmethodtoreferdirectlytotheworksheetthat

currentlyhasthefocus,orrefertoaspecificworksheetasa

memberoftheWorksheetscollection.

Forexample,tosetthetextforallcellsinthecurrent

worksheettobold,youcanuseeitherofthevariablesinthe

precedingexampletoreturnanobjectthatrepresentsallthe

cellsintheworksheet:

ws1.Cells.Font.Bold=True



Youcouldaccomplishthesametaskforthecurrentworksheet



byusingtheActiveSheetproperty,whichrepresentstheactive

worksheet.Thisisthemostcommonwaytorefertothe

propertiesandmethodsofthecurrentlyactiveworksheet:

ActiveSheet.Cells.Font.Bold=True



Youcanalsorefertoaspecificworksheetasamemberofthe

Worksheetscollection:

Worksheets("WombatBattingAverages").Cells.Font.Bold=True



9.1.1.GetCellsinaWorksheet

Asyousawinthepreviousexamples,youcanusetheCells

propertyofaworksheettoworkwithallthecellsona

worksheetasagroup.Twootherwaysyoucanworkwith

rangesofcellsinaworksheetareto:

UsetheRangepropertytoworkwithaspecificrangeofcells

UsetheUsedRangepropertytoworkwithonlycellsthathave

data

Forexample,youcouldusetheRangepropertytosetthetextof

cellsintherangeC5:D10ontheactiveworksheettoboldtype:

ActiveSheet.Range("C5:D10").Font.Bold=True



TheRangepropertymaybethemostcommonlyusedpropertyin



Excelprogramming.Youwilluseitalot!

TheUsedRangepropertyreturnstherectangularblockofcellsthat

containvalues.Theupper-leftcorneroftheblockisthefirstcell

thatcontainsavalue,andthelower-rightcorneroftheblockis

thelastcellthatcontainsavalue.Inbetweentheremayormay

notbeemptycellstherangeiscontiguous.It'smoreefficientto

workwithUsedRangethantheCellspropertybecauseitreturnsa

smaller,morespecificrangeofcells.Forexample,thefollowing

codeselectsallofthecellsthathavenegativevaluesonthe

activeworksheet:

SubDemoUsedRange()

DimcelAsRange,strAsString

ForEachcelInActiveSheet.UsedRange

Ifcel.Value<0Thenstr=str&cel.Address&","

Next

Ifstr<>""Then_

ActiveSheet.Range(Left(str,Len(str)-1)).Select

EndSub



9.2.WorksheetsandWorksheetMembers

UsetheWorksheetscollectiontocreatenewandgetexisting

worksheetsinExcel.UsetheWorkbookobject'sWorksheetsmethod

togetareferencetothiscollection.UsetheWorksheetobjectto

activateandworkwithrangesonindividualworksheets.The

WorksheetscollectionandWorksheetobjecthavethefollowing

members.Keymembers(showninbold)arecoveredinthe

followingreferencesection:



Activate



Add1



Application2



AutoFilter



AutoFilterMode



Calculate



Cells



ChartObjects



CheckSpelling



CircleInvalid



CircularReference



ClearArrows



ClearCircles



CodeName



Columns



Comments



ConsolidationFunction



ConsolidationOptions



ConsolidationSources



Copy2



Count1



Creator2



CustomProperties



Delete



DisplayPageBreaks



DisplayRightToLeft



EnableAutoFilter



EnableCalculation



EnableOutlining



EnablePivotTable



EnableSelection



Evaluate



FillAcrossSheets1



FilterMode



HPageBreaks2



Hyperlinks



Index



Item



ListObjects



MailEnvelope



Move2



Name



Names



Next



OLEObjects



Outline



PageSetup



Parent2



Paste



PasteSpecial



PivotTables



PivotTableWizard



Previous



PrintOut2



PrintPreview2



Protect



ProtectContents



ProtectDrawingObjects



Protection



ProtectionMode



ProtectScenarios



QueryTables



Range



ResetAllPageBreaks



Rows



SaveAs



Scenarios



Scripts



ScrollArea



Select2



SetBackgroundPicture



Shapes



ShowAllData



ShowDataForm



SmartTags



StandardHeight



StandardWidth



Tab



TransitionExpEval



TransitionFormEntry



Type



Unprotect



UsedRange



Visible2



VPageBreaks2



XmlDataQuery



XmlMapQuery



1Collectiononly



2Objectandcollection



worksheet.Activate()



Activatesthespecifiedworksheetgivingitfocus.Forexample,

thefollowingcodeactivatestheWombatBattingAverages

worksheet:

Worksheets("WombatBattingAverages").Activate



worksheets.Add(Before,After,Count,Type)



Createsoneormoreworksheets.Ifyoucreateasingle

worksheet,itistheactivesheet.Ifyoucreatemorethanone

worksheet,thelastsheetcreatedistheactivesheet.

Argument Settings



Before



Specifiesanexistingworksheetifyouwanttoplacethenewworksheetbefore

thatsheet.



After



Specifiesanexistingworksheetifyouwanttoplacethenewworksheetafter

thatsheet.



Count



Specifiesthenumberofsheetstobeaddedifyouwanttocreatemorethan

onesheet.



Type



UsexlCharttoinsertachart,xlExcel4MacroSheettoinsertamacrosheet,orthe

pathtoatemplateifyouareinsertingasheetbasedonanexistingtemplate.



Thefollowingcodecreatestwoworksheetsafterthe

WombatBattingAveragesworksheet:



ActiveWorkbook.Sheets.AddAfter:=Worksheets("WombatBattingAvera



worksheet.Calculate()



Calculatestheformulasonthespecifiedworksheet.For

example,thefollowingcodecalculatestheformulasforthe

battingaveragesofarenownedsoftballteam:

Worksheets("WombatBattingAverages").Calculate



worksheet.Cells



ReturnsaRangeobjectthatrepresentscellsontheworksheet.

ThesyntaxshowstheCellspropertywithoutarguments,which

returnsallthecellsinaworksheetasaRangeobject.However,

youcanalsoenterthespecificrangeyouwanttoreturnasif

youwereusingthesyntaxforaRangeobject.

Thefollowingcodesetsthefontsizeto12foreverycellinthe

WombatBattingAveragesworksheetsotheathletescaneasily

readthem:

Worksheets("WombatBattingAverages").Cells.Font.Size=12



Thefollowingcodehighlightsbattingaverages.300andover:



DimrwIndexAsInteger

ForrwIndex=1To3

WithWorksheets("WombatBattingAverages").Cells(rwIndex,2)

If.Value>=0.3Then

.Font.Color=RGB(255,0,0)

EndIf

EndWith

NextrwIndex



worksheet.CheckSpelling(CustomDictionary,

IgnoreUppercase,AlwaysSuggest,SpellLang)



Checksthespellingoftextonthespecifiedworksheetand

displaystheSpellingdialogbox.

Thefollowingcodechecksthespellingoftextinthecellsofthe

WombatBattingAveragesworksheet:

Worksheets("WombatBattingAverages").CheckSpelling



worksheet.Columns([Index])



ReturnsaRangeobjectthatrepresentsthecolumnspecifiedby

Indexorallthecolumnsinaworksheet.

Thefollowingcodeselectsthesecondcolumn(columnB)inthe

activeworksheet:

ActiveSheet.Columns(2).Select



worksheet.Comments



Returnsthecollectionofcommentsonaworksheet.

ThefollowingcodedeletescommentsbyJeffWebb:

DimcmtAsComment

ForEachcmntinActiveSheet.Comments

Ifcmnt.Author="JeffWebb"Thencmnt.Delete

Next



worksheet.Copy(Before,After)



Copiesthespecifiedsheettoanotherlocationintheworkbook.

Argument Settings



Before



Specifiesanexistingworksheetifyouwanttoplacethecopiedworksheet

beforethatsheet



After



Specifiesanexistingworksheetifyouwanttoplacethecopiedworksheetafter

thatsheet



ThefollowingcodecopiestheKarmaFactorworksheetafterthe

WombatBattingAveragesworksheet:

ActiveWorkbook.Worksheets("KarmaFactor").Copy

After:=Worksheets("WombatBattingAverages")



worksheet.DisplayPageBreaks



SetthispropertytoTruetodisplaypagebreaksforthe

worksheet.

worksheet.EnableCalculation[=setting]



Trueallowscalculationsontheworksheet;Falsedisables

calculations.DefaultisTrue.

worksheet.EnableOutlining[=setting]



SetthispropertytoTruetoautomaticallyenableoutlining

symbolsontheworksheet.

worksheet.EnablePivotTable[=setting]



SetthispropertytoTruetoautomaticallyenablePivotTable

controlsandactionsontheworksheet.

worksheet.EnableSelection[=setting]



Setthispropertyto:



xlNoSelection

Topreventanyselectionontheworksheet



xlNoRestrictions



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

Chapter 9. Working with Worksheets and Ranges

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

×