一楼
标题:选中工作表中真正有数据的区域
问题:当表中有格式,如颜色填充时,用usedrange会把没有数据的部分也选中
思路:利用SpecialCells选中有数据的Areas,遍历每个area找出四个角的单元格
代码:
Sub MyUserRange()
Dim rA As Range, rB As Range, rC As Range, rD As Range
Dim toprow As Long, bottommost As Long, leftmost As Integer, rightmost As Integer
If TypeName(Selection) <> "Range" Then Exit Sub
On Error Resume Next
Set rA = Cells.SpecialCells(xlConstants)
Set rB = Cells.SpecialCells(xlFormulas)
rA.Select
rB.Select
Union(rA, rB).Select
On Error GoTo 0
Set rC = Selection
toprow = rC.Areas(1).Rows(1).Row
bottommost = rC.Areas(1).Rows(rC.Areas(1).Rows.Count).Row
leftmost = rC.Areas(1).Columns(1).Column
rightmost = rC.Areas(1).Columns(rC.Areas(1).Columns.Count).Column
For Each rD In rC.Areas
If rD.Rows(1).Row < toprow Then toprow = rD.Rows(1).Row
If rD.Rows(rD.Rows.Count).Row > bottommost Then bottommost = rD.Rows(rD.Rows.Count).Row
If rD.Columns(1).Column < leftmost Then leftmost = rD.Columns(1).Column
If rD.Columns(rD.Columns.Count).Column > rightmost Then rightmost = rD.Columns(rD.Columns.Count).Column
Next rD
Range(Cells(toprow, leftmost), Cells(bottommost, rightmost)).Select
End Sub
用途例子:删除多余的空行
Sub DeleteEmptyRows()
Dim rS As Range, rA As Range
Dim lFirstRow As Long
Call UsedSelect
Set rS = Selection
lFirstRow = rS.Rows(rS.Rows.Count).Row + 1
Set rA = Range(Rows(lFirstRow), Rows(Rows.Count))
rA.Select
If MsgBox("Are you sure for DELETE selection rows?" & vbCr & rA.Address, vbYesNo, "Delete empty rows!") = vbYes Then
rA.delete Shift:=xlTop
End If
End Sub
标题:选中工作表中真正有数据的区域
问题:当表中有格式,如颜色填充时,用usedrange会把没有数据的部分也选中
思路:利用SpecialCells选中有数据的Areas,遍历每个area找出四个角的单元格
代码:
Sub MyUserRange()
Dim rA As Range, rB As Range, rC As Range, rD As Range
Dim toprow As Long, bottommost As Long, leftmost As Integer, rightmost As Integer
If TypeName(Selection) <> "Range" Then Exit Sub
On Error Resume Next
Set rA = Cells.SpecialCells(xlConstants)
Set rB = Cells.SpecialCells(xlFormulas)
rA.Select
rB.Select
Union(rA, rB).Select
On Error GoTo 0
Set rC = Selection
toprow = rC.Areas(1).Rows(1).Row
bottommost = rC.Areas(1).Rows(rC.Areas(1).Rows.Count).Row
leftmost = rC.Areas(1).Columns(1).Column
rightmost = rC.Areas(1).Columns(rC.Areas(1).Columns.Count).Column
For Each rD In rC.Areas
If rD.Rows(1).Row < toprow Then toprow = rD.Rows(1).Row
If rD.Rows(rD.Rows.Count).Row > bottommost Then bottommost = rD.Rows(rD.Rows.Count).Row
If rD.Columns(1).Column < leftmost Then leftmost = rD.Columns(1).Column
If rD.Columns(rD.Columns.Count).Column > rightmost Then rightmost = rD.Columns(rD.Columns.Count).Column
Next rD
Range(Cells(toprow, leftmost), Cells(bottommost, rightmost)).Select
End Sub
用途例子:删除多余的空行
Sub DeleteEmptyRows()
Dim rS As Range, rA As Range
Dim lFirstRow As Long
Call UsedSelect
Set rS = Selection
lFirstRow = rS.Rows(rS.Rows.Count).Row + 1
Set rA = Range(Rows(lFirstRow), Rows(Rows.Count))
rA.Select
If MsgBox("Are you sure for DELETE selection rows?" & vbCr & rA.Address, vbYesNo, "Delete empty rows!") = vbYes Then
rA.delete Shift:=xlTop
End If
End Sub