2016-11-10 18 views
0

我在編寫代碼以刪除單元格中包含特定字符串的列。代碼如下:用於刪除包含具有函數的特定字符串的列的VBA代碼單元格

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)).Interior.ColorIndex = 6 

更換

Range(.Cells(1, j), .Cells(.Rows.Count, j)).Delete Shift:=xlToLeft 

它正確地強調了所有我想要刪除的細胞。

+0

向後時刪除行或列總循環,'對於J = .Columns.Count要2步驟-1' –

+0

感謝您的回答。 – Koskarium

回答

1

當用循環刪除行時,應該總是向後運行,就像刪除某行時一樣,j增加1並表示跳過一行。

更換

For j = 2 To .Columns.Count 

對於

For j = .Columns.Count To 2 Step -1 
+0

要明確,'步驟-1'會讓我回到一個單元格,在這種情況下,從最後? – Koskarium

+0

是的,這將從最後一行開始,並通過您的數據反向工作。這確保沒有行被跳過。當向前運行時,假設j = 5並刪除該行,這意味着行6現在是行5,但是j現在等於6,所以原始行6一起被遺漏。 –

+0

哦,那就是爲什麼;有道理。感謝您的時間和智慧。 – Koskarium

相關問題