Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 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 Answer

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...