我需要一种方法来选择一个包含数千个空单元格的列,直到包含数据的最后一行(通常在非相邻列中),然后用公式填充选择。到目前为止,我一直在使用ctrl +↓来查找我知道不是空的列的最后一行,并使用它作为参考点来确定我的范围。有没有办法在VBA中更快地完成这项工作?我对VBA很陌生,但如果能做到这一点,我的工作就会轻松得多。提前致谢! :)
答案 0 :(得分:0)
查找工作表中包含值的最后使用过的单元格的一些可靠方法:
Option Explicit
Sub lastUsedCells() 'optimised for performance
Dim maxRow As Long
Dim maxCol As Long
With ActiveSheet
If WorksheetFunction.CountA(.UsedRange) > 0 Then 'if sheet is not empty
With .UsedRange 'restrict search area to UsedRange; (includes formats)
maxRow = .Rows.Count + 1 'last row in UsedRange
maxCol = .Columns.Count + 1 'last col in UsedRange
'first cell not empty in col A
If Len(.Cells(1, 1)) = 0 Then MsgBox .Cells(1, 1).End(xlDown).Row
'first cell not empty in row 1
If Len(.Cells(1, 1)) = 0 Then MsgBox .Cells(1, 1).End(xlToRight).Column
MsgBox .Cells(maxRow, 1).End(xlUp).Row 'last row in column A
MsgBox .Cells(1, maxCol).End(xlToLeft).Column 'last column in row 1
MsgBox .Find( _
What:="*", _
After:=.Cells(1, 1), _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row 'last row (longest col)
MsgBox .Find( _
What:="*", _
After:=.Cells(1, 1), _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column 'last col (longest row)
End With
Else
MsgBox "Sheet " & .Name & " is empty"
End If
End With
End Sub