Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

vba - Excel Fully Qualifying Range (Cells(),Cells())

I know many people have talked about fully qualifying ranges. I just want to know how deep you need to go with it to avoid problems.

In the example, I have qualified my worksheet using a dimensioned variable. Is it then necessary to be 100% reliable, to further qualify within the range parentheses?

dim myWS as Worksheet
set myWS = Thisworkbook.Activesheet

-- Use method A?

myWS.Range(Cells(1,5), Cells(500,20)).ClearContents

-- Or method B?

myWS.Range(myWS.Cells(1,5), myWS.Cells(500,20)).ClearContents

Does "Cells" inside Range parentheses default to reference myWS.Range in which it was called or does "Cells" default to reference the active sheet?

If myWS were set to a sheet other than the active sheet, would I get unexpected results from Cells?

It's not hard, except I will have to go back and change it in many places if you say that the second way is more trustworthy!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Method A will only work if you myWS is active at the time of being called. Method B is more robust, as are method C:

myWS.Range(Cells(1,5).Address, Cells(500,20).Address).ClearContents 

or method D:

myWS.Range("E1:T500")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...