Excel将选区大小调整为使用的范围



我有一个宏,循环遍历选定范围内的所有单元格,并对每个单元格做一些事情。在本例中,它将大写每个单元格的内容。

问题是,如果用户选择整个列,这需要很长时间才能完成。我希望有一种方法来缩小rng在表.UsedRange。这样,它就不会尝试遍历列中的所有1,048,576个单元格。

如何调整rng的大小,以在选定的工作表上使用的单元格内?

Public Sub Uppercase_Selected_Cells()
Dim rng As Range
Set rng = Selection

'--- Reduce rng to be within the used cells here ---

For Each cell In rng
If Not cell.HasFormula Then
cell.Value = UCase(cell.Value)
End If
Next cell

End Sub

SelectionUsedRange上使用Intersect,并确保测试结果不是Nothing:

Set rng = Intersect(Selection, ActiveSheet.UsedRange)
If Not rng Is Nothing Then
' keep processing
End If

最新更新