excel - 使用 VBA 清除格式很慢,下面的代码可以以更好的方式重写
问题描述
代码用于删除当前格式,删除格式基于单元格值 = 3 在列
Sub Format1()
Dim I As Long
Dim LastRow As Long
Dim lrowno As Long
Application.ScreenUpdating = False
LastRow = Range("B" & Rows.count).End(xlUp).Row
For lrowno = 4 To LastRow
If Range("A" & lrowno).Value = 3 Then
Range("H" & lrowno, "I" & lrowno).ClearFormats
End If
lrowno = lrowno + 4
Next lrowno
MsgBox ("Report is Generated")
End Sub
解决方案
为了提高速度,您应该将单元格读/写操作的数量减少到最低限度。因此,您可以将整个 A 列读入一个数组(以检查那里的值)并收集您想要在变量中清除格式的所有范围
RangeToClear
。lrowno = lrowno + 4
永远不要在For
循环中弄乱计数器变量。要么使用Do
循环,您可以自己增加计数器,要么使用Step 5
to makeNext
increase by5
代替 by1
。
Option Explicit
Public Sub FormatReport()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1") 'specify your sheet
Dim LastRow As Long
LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
Dim ValuesOfColumnA() As Variant 'read column A into an array for faster data access!
ValuesOfColumnA = ws.Columns(1).Value
Dim RangeToClear As Range
Dim iRow As Long
For iRow = 4 To LastRow Step 5
If ValuesOfColumnA(iRow, 1) = 3 Then 'checking the array is much faster than checking the cell!
If RangeToClear Is Nothing Then 'first range to clear
Set RangeToClear = ws.Range("H" & iRow, "I" & iRow)
Else 'append/union all the other ranges to clear
Set RangeToClear = Application.Union(RangeToClear, ws.Range("H" & iRow, "I" & iRow))
End If
End If
Next iRow
'if something to clear was found then clear
If Not RangeToClear Is Nothing Then
RangeToClear.ClearFormats
End If
MsgBox "Report is Generated"
End Sub
推荐阅读
- angular - Should i disable change detection during angular app init phase?
- apache-kafka - Create schema from JSON to write Parquet to HDFS with Kafka Sink
- c# - 良好实践 - C# 中的私有事件与私有方法
- javascript - Angular 2 - 使用 AOT 构建:Javascript 堆内存不足
- swift - 压缩我的音频文件后,为什么我不能播放文件?
- c# - 使用 .net 核心声纳扫描仪将声纳结果发布到 tfs 构建
- node.js - find all documents of all collections in db of mongoose using express
- ios - 斯威夫特:如何使所有正在运行的计时器无效?
- r - dplyr 按变量等级折叠但忽略 NA
- ios - MTLDevice 类需要 id<>