将范围设置为所有填充的单元格
我需要设置一个范围来只select包含数据的行中的单元格。
有时在第3行的列B,C,D,E和F中会有数据,而在其他时间,在该行的前10或20列中会有数据。
我已经尝试了下面,但它不起作用。
Dim rRng As Range Set rRng = Sheets(1).Range("B3").End(xltoright)
我知道我很有标志,但我正在为此而挣扎。
此代码将运行各种不同的数据集; 有时需要select五个单元格,有时需要十个(如果填充)。
select到最后一列或select非空白
Sub SelectLstCol() Dim Col As Long Dim rng As Range Col = Cells(3, Columns.Count).End(xlToLeft).Column Set rng = Range(Cells(3, 2), Cells(3, Col)) rng.Select 'or whatever you want to do with it End Sub Sub NonBlanks() Dim Col As Long Dim rng As Range Col = Cells(3, Columns.Count).End(xlToLeft).Column Set rng = Range(Cells(3, 2), Cells(3, Col)).SpecialCells(xlCellTypeConstants, 23) rng.Select 'or whatever you want to do with it End Sub
使用函数可以更轻松地重用它:
Sub test_andrew_abbott() MsgBox Get_Row_Range(5).Address MsgBox Get_Row_Range(Range("A12").Row).Address End Sub
这将比.End(xlToRight)
更强大:
Public Function Get_Row_Range(RowNumber As Long) As Range Dim wS As Worksheet, _ rRng As Range Set wS = Sheets(1) With wS Set rRng = .Range(.Range("A" & RowNumber), _ .Cells(RowNumber, .Columns.Count).End(xlToLeft)) End With Set Get_Row_Range = rRng End Function
你可以连接到你的Excel文件作为一个数据集,我发现它比其他方式更好