我正在编写一个代码来摆脱包含单元格中特定字符串的列。代码如下:
Dim i As Integer
Dim j As Integer
Dim state As String
Dim num As Variant
num = InputBox("Enter the state", "What stx is it?", "Enter x here")
'the & will combine them together
state = "st" & num
With ActiveSheet.UsedRange
'Uses all the columns in use due to the previous line
For j = 2 To .Columns.Count
If .Cells(2, j).Formula = state Then
'Do nothing
Else
Range(.Cells(1, j), .Cells(.Rows.Count, j)).Delete Shift:=xlToLeft
End If
Next j
End With
End Sub
我从j=2
开始,因为我不想删除第一列。
Here is a snippet of my data I am trying to modify.
但是,这不会擦除包含特定单元格的所有列。令我困惑的是,如果我更换
Range(.Cells(1, j), .Cells(.Rows.Count, j)).Delete Shift:=xlToLeft
带
Range(.Cells(1, j), .Cells(.Rows.Count, j)).Interior.ColorIndex = 6
它正确突出显示我要删除的所有单元格。
答案 0 :(得分:1)
删除带循环的行时,应始终向后运行,如删除行时,j增加1,表示您跳过一行。
替换
For j = 2 To .Columns.Count
有关
For j = .Columns.Count To 2 Step -1