函数删除列需要运行6次才能按预期工作

我写了下面的macros。

Sub SeasonTeas() Dim lastColumn As Long lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column Dim ArrSize As Long ArraySize = lastColumn - 1 Dim elem As Long ReDim SelectColumns(ArraySize) For x = 1 To (lastColumn) If Cells(1, x).Value <> "respid" And Cells(1, x).Value <> "status" And Cells(1, x).Value <> "CID" Then Columns(x).Select Selection.Delete Shift:=xlToLeft End If Next x End Sub 

我需要find与respid / status / CID不匹配的列,并删除其他所有内容。

它需要运行6次来做我所需要的。

我知道有可能是一种更有效的方法,但是我想在尝试其他方法之前先这样做。

您需要运行六次macros以获得所需结果的原因是,当您删除一列时,其余列将移动到左侧,并且立即在已删除列右侧的列未在下一个循环迭代。

例如,第1列被删除,所以第2列变为第1列,但在下一个循环,x = 2,所以新的第1列不会被testing。

 Sub SeasonTeas2() Dim lastColumn As Long Dim x As Long 'Define your last column lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column 'Step backwards from your last column For x = lastColumn To 1 Step -1 If Cells(1, x).Value <> "respid" And Cells(1, x).Value <> "status" And Cells(1, x).Value <> "CID" Then Columns(x).Delete Shift:=xlToLeft End If Next x End Sub 

使用F8浏览你的代码可以让你看到每个命令在执行时的function,这样你就可以看到你的代码是否按照你的预期运行。