我正在尝试编写一些VBA,它将检查一系列列(行M到GD)中单元格的值,如果该单元格不包含“ YY”,则删除该列。
要检查的单元格始终在第22行中
我尝试了以下方法,但是速度很慢。
w = 186
Do
If Worksheets(“SOF”).Cells(22, w).Formula = "YY" Then
w = w - 1
Else
Worksheets(“SOF”).Cells(22, w).EntireColumn.Delete
End If
w = w - 1
Loop Until w < 13
是否有人对如何加快此速度或解决此问题的更好方法有任何建议?
谢谢
是否有人对如何加快此速度或解决此问题的更好方法有任何建议?
是的。不要删除循环中的列。使用Union
方法。这是一个例子。我已经注释了代码,因此您在理解它时不会遇到问题。如果您仍然这样做,则只需回发。
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim i As Long
Dim delRange As Range
'~~> Set this to the relevant worksheet
Set ws = ThisWorkbook.Sheets("SOF")
With ws
'~~> Loop through relevant columns
For i = 13 To 186
'~~> Check if the value is equal to YY
If UCase(Trim(.Cells(22, i).Value)) = "YY" Then
'~~> Store the Range to delete later
If delRange Is Nothing Then
Set delRange = .Columns(i)
Else
Set delRange = Union(delRange, .Columns(i))
End If
End If
Next i
End With
'~~> Delete the relevant columns in one go
If Not delRange Is Nothing Then delRange.Delete
End Sub
只需眨眼即可执行,但如果需要,可以将代码夹在Application.ScreenUpdating = False
和之间Application.ScreenUpdating = True
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句