简体   繁体   中英

Why can't I use a single “Cells” reference as a “Range” parameter

This question: Copy from one workbook to another made me realize that while I knew how to fix the issue described, I didn't know why it caused an error.

Range("A1").Select is fine.

Range(Cells(1,1),Cells(1,1)).Select is fine.

Range(Cells(1,1).Address).Select is fine.

Range(Cells(1,1)).Select returns an Application defined or Object defined error

Is this a bug, or is there a deeper reason that I don't understand?

Cells(1,1) evaluates to the value of what is located in that cell.

It is equivalent to Cells(1,1).Value

You would have the same issue with Range(Range("A1")).Select

To expand a little:

Range("A1").Select is fine.

Pretty straightforward as to why.

Range(Cells(1,1),Cells(1,1)).Select is fine.

Yes, this ends up being equivalent to Range(A1:A1)

Range(Cells(1,1).Address).Select is fine.

This ends up being equivalent to Range("$A$1") This is because the .Address part resolves to the cell's address.

Range(Cells(1,1)).Select returns an Application defined or Object defined error

The error is because VB tried to resolve this but can't, since it's just a single cell (and a Range is multiple cells (or at least the same cell listed twice, as the second example above)). But, unlike the third example, there's nothing telling VBA to use Cells(1,1) 's address, this is just a reference to the cell in general...therefore, VB doesn't know what to do with it really...do you want the Cells(1,1).Font , or the .Value , or the .Row , etc...

I hope that helps a little, but check out the link @Soulfire provided, and you can Google around for more details on Range() if it's still unclear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM