如何使用VBA检查Excel范围是代表整行还是列?
我需要确定一个给定的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")
谢谢。
你可以使用这样的东西:
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
行数和列数在Excel中是常量(取决于Excel版本):
所以,您只需要计算范围内的行和列,并将这些值与行和列的默认值进行比较
您可能能够parsingrng.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
这将在所有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
我的0.02美分
Select Case rng.Address Case rng(1).EntireColumn.Address MsgBox "column" Case rng(1).EntireRow.Address MsgBox "row" End Select
其中rng
是Range
types的variables