[英]VBA Remove format from empty cells in Excel (while ignoring the merged cells)
[英]VBA Remove format from empty cells in Excel
我需要一个快速代码来清理所有空单元格的格式。 我已经写了这段代码,但它太慢了。 有没有办法让它更快?
Sub removeFormatEmpty()
'Declaration of variables
Dim sheet As Worksheet
Dim rcell As Range
For Each sheet In Worksheets
sheet.Activate
'Cells.UnMerge
For Each rcell In sheet.UsedRange.Cells
If rcell.MergeCells = True Then
rcell.UnMerge
End If
If rcell.Value = "" Then
rcell.ClearFormats
End If
Next rcell
Next sheet
End Sub
这段代码可以工作,但是它很慢,因为它需要逐个单元地进行。 有没有办法选择除包含内容的单元格之外的整个范围?
更新:感谢 bobajob 和 jordan 的评论,我已经能够更新代码并使其更快和优化。 这是新代码:
Sub removeFormatEmptyImproved()
Dim sheet As Worksheet
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
For Each sheet In Worksheets
'sheet.Activate
sheet.UsedRange.SpecialCells(xlCellTypeBlanks).ClearFormats
Next sheet
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
所以现在解决了。
首先,您不必在取消合并之前检查单元格是否已合并。 因此,要取消合并工作sheet
所有单元格...
sheet.UsedRange.UnMerge
您无需在更改工作表之前激活它
如评论中所述,您可以使用
sheet.UsedRange.SpecialCells(xlCellTypeBlanks).ClearFormats
将Calculation
转为手动并将ScreenUpdating
转为 false 是加快大多数 VBA 代码速度的简便方法!
Application.Calculation = xlCalculationManual Application.ScreenUpdating = False ' <other code> ' Include error handling so that these are always set back! Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True
所以你产生的Sub
将是
Sub removeFormatEmpty()
Dim sheet As Worksheet
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
For Each sheet In ThisWorkbook.Worksheets
sheet.UsedRange.UnMerge
sheet.UsedRange.SpecialCells(xlCellTypeBlanks).ClearFormats
Next sheet
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
加快速度的最后一步是深入了解您的UsedRange
。 它可能因记住长期未使用的细胞并且远远超出必要而臭名昭著。 如果您知道您的工作表布局,则可能有一种方法可以限制您正在使用的范围。
在此处查看执行此操作的一些方法: Getting the actual usedrange
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.