你能在其With块中引用一个对象吗?

时间:2016-03-17 16:49:22

标签: vba excel-vba excel

在“With”块中,有没有办法引用块本身的主题?

例如,如果我想将文本从下面的单元格复制到单元格中,我可以说:

With MyRange    
    .cells(1).offset(1,0).copy .cells(1)
End With

但我也可以这样做吗?

With MyRange.cells(1)   
    .offset(1,0).copy [???]
End With

“[???]”将是一种简单的说法“MyRange.Cells(1)”。

2 个答案:

答案 0 :(得分:5)

.Cells可行,因为Cells属性将返回范围本身。

With MyRange.cells(1)   
    .offset(1,0).copy .Cells
End With

原因是:.Cells属性返回一个范围对象,您可以对该范围对象使用.Cells,并进一步扩展到任何属性,返回范围,例如:

With Sheet1.ListObjects(1).ListColumns(1).DataBodyRange
    Debug.Print .Cells.Address  '#returns the address of entire "self" range in specified column's DataBodyRange
End With

ListObject的{​​{3}}属性返回RangeListColumnsHeaderRowRange等也是如此。任何表示范围的对象的任何属性都会返回一个范围。这些其他对象不是它们自己的类,而是另一个对象的属性,它返回Range

这适用于单细胞或多细胞范围。当然,如果您需要操作单个单元格,.Cells可以进行微调,例如:.Cells(1)等。

答案 1 :(得分:3)

您可以使用偏移(0)来引用自身:

With MyRange.cells(1)   
    .Offset(1).Copy .Offset(0)
End With