我需要确定给定的Range对象是实际上是整列还是整行,或者两者都不是。
我现在所做的是基于下一个适合我的代码。
If Range.Rows.Count = Range.EntireColumn.Rows.Count Then
...
ElseIf Range.Columns.Count = Range.EntireRow.Columns.Count Then
...
End If
我想知道是否有更高效和/或更优雅的方式做同样的事情?也许,我忽略了一些内置财产?
UPD:我得到的范围是:
Worksheet.Range("NamedRange")
感谢。
答案 0 :(得分:2)
这适用于所有Excel版本:
Function cellsInRange(rng As Range) As Boolean
Dim cellsInCol As Long, cellsInRow As Long, cols As Long, count As Long, rws As Long
With ActiveSheet
cellsInCol = .Columns("A").Cells.count
cellsInRow = .Rows(1).Cells.count
End With
With rng
cols = .Columns.count
count = .Cells.count
rws = .Rows.count
End With
If cols = 1 And count = cellsInCol Then
cellsInRange = True
ElseIf rws = 1 And count = cellsInRow Then
cellsInRange = True
End If
End Function
修改强>
如果需要有关范围对象的更多具体细节,则以下调整可能有用:
Function cellsInRange(rng As Range) As String
Dim cellsInCol As Long, cellsInRow As Long, cols As Long, count As Long, rws As Long
With ActiveSheet
cellsInCol = .Columns("A").Cells.count
cellsInRow = .Rows(1).Cells.count
End With
With rng
cols = .Columns.count
count = .Cells.count
rws = .Rows.count
End With
If cols = 1 And count = cellsInCol Then
cellsInRange = "Single column"
ElseIf rws = 1 And count = cellsInRow Then
cellsInRange = "Single row"
Else
cellsInRange = "Neither single column nor single row"
End If
End Function
答案 1 :(得分:2)
由于我认为OP自己的问题包含一个很好的答案(对于大多数用途),三年后没有人发布它,所以就在这里。我将相同的逻辑转换为这两个函数:
Function IsEntireRow(ByVal Target As Excel.Range) As Boolean
IsEntireRow = Target.Columns.Count = Target.EntireRow.Columns.Count
End Function
Function IsEntireColumn(ByVal Target As Excel.Range) As Boolean
IsEntireColumn = Target.Rows.Count = Target.EntireColumn.Rows.Count
End Function
答案 2 :(得分:1)
你可以使用这样的东西:
Sub somethinglikethis()
Dim rRange As Range
Set rRange = Range("A:A")
With rRange
If .Rows.Count = 1048576 And .Columns.Count < 16384 Then
Debug.Print "Range represents Column(s)"
ElseIf .Rows.Count < 1048576 And .Columns.Count = 16384 Then
Debug.Print "Range represents row(s)"
ElseIf .Rows.Count = 1048576 And .Columns.Count = 16384 Then
Debug.Print "Range represents whole sheet"
Else
Debug.Print "Range represents none of row(s) or column(s)"
End If
End With
End Sub
所以,你只需要计算范围内的行和列,并将这些值与行和列的默认值进行比较
答案 3 :(得分:1)
您可以解析rng.Address(0,0)
;用英语(而不是VBA):
s = rng.Address(0,0)
If s contains no letters then rng contains only full rows
If s contains no numbers then rng contains only full columns
答案 4 :(得分:1)
我的0,02美分
Select Case rng.Address
Case rng(1).EntireColumn.Address
MsgBox "column"
Case rng(1).EntireRow.Address
MsgBox "row"
End Select
其中rng
是Range
类型