Excel Range
类似乎有一个未记录的属性,用于确定 Item
、Cells
和 Count
属性有效(很可能还有其他类方法和属性)。
普通Range
似乎具有“Cell”属性;即访问它们的属性需要单元索引。
Set x = [A1:H50]
?TypeName(x)
Range
?x.Address
$A$1:$H$50
?x.Count
400
?x(20).Address
$D$3
但是您也可以获得“列”或“行”配置的Range
,其行为有所不同。
Set x = [A1:H50].Columns
?TypeName(x)
Range
?x.Address
$A$1:$H$50
?x.Count
8
?x(20).Address
$T$1:$T$50
我正在尝试为 Range
编写一个包装类,它的行为比多 Area
范围的内置类型更好。我想更好地了解这个范围“处置”是如何运作的。是否有内置属性或其他简单的方法来测试 Range
对象具有什么“配置”? “处置”是范围的不可变属性,还是有办法在不使用“行”、“列”或“单元格”属性获取新范围的情况下更改它?
最佳答案
我根本不知道这种行为的存在。我查看了 Range 对象的属性列表,但找不到任何可以满足包装器这一需求的内容。相反,我编写了一个函数,我认为它可以告诉您“处置”,我将其称为方向。
Function getOrientation(ByVal Rng As Range) As String
'If only one row, it's a column orientation
If Rng.Rows.Count = 1 Then
getOrientation = "Column"
Exit Function
End If
'If only one column, it's a row orientation
If Rng.Columns.Count = 1 Then
getOrientation = "Row"
Exit Function
End If
'If the cell count matches the expected cell count, it's Both
If Rng.Count = Rng.Columns.Count * Rng.Rows.Count Then
getOrientation = "Both"
ElseIf Rng.Count = Rng.Columns.Count Then
getOrientation = "Column"
Else
getOrientation = "Row"
End If
End Function
Sub Test()
'Testing
Debug.Print getOrientation(Range("A1:B100").Columns)
Debug.Print getOrientation(Range("A1:B100").Rows)
Debug.Print getOrientation(Range("A1:B100"))
Debug.Print getOrientation(Range("A1:A100"))
Debug.Print getOrientation(Range("A1:C1"))
End Sub
关于vba - Excel 范围按行或列排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39900916/