2017-02-10 184 views
3

這就是我所需要的:範圍說列F:F,G:G,K:K。如果單元格僅爲這些特定列的零或空白,請刪除整列。如果有任何其他價值,則不採取任何行動。刪除範圍內的空白或零列

下面給出的是我現在使用的。但是這會刪除不應刪除的其他列。

LastRow = Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row 
LastColumn = Sheets("Sheet1").Cells(9, Columns.Count).End(xlToLeft).Column 
lastcol_name_1 = Replace(Cells(1, LastColumn).Address(False, False), "1", "") 

'to find letter of last column 

With Sheets("Sheet1")   
    For i = 1 To LastColumn 
     lastcol_name_1 = Replace(Cells(1, i).Address(False, False), "1", "") 'to find letter of last column 
     If(lastcol_name_1=「K」 or lastcol_name_1=」L」 or lastcol_name_1=」M」) then ‘write the column name here 
      If Evaluate("sum(countif(" & .Range(.Cells(10, i), _ 
       .Cells(LastRow, i)).Address & ",{"""",0}))") = LastRow - 10 + 1 Then _ 
       .Columns(i).Delete 
     Endif 
    Next i 
+1

迭代向後:'對於i = LastColumn 1步-1' –

+0

此外,而不是建立和解析字符串爲什麼不使用'如果我> = 11然後我= 13然後' –

+1

@ScottCraner這肯定會工作,但實際上我發現使用範圍對象,並通過聯合添加範圍,然後在最後調用刪除總是更快。你是否同意或者這是一個明顯的監督我的一部分? – Zerk

回答

0

如果我正確理解你下面要刪除列「F」,「G」和「K」,如果他們是空的,其餘的列左移 - 假設這是你想要做什麼這裏。我已經離開儘可能多的代替你自己的代碼,我可以:

Sub main(): 

    LastColumn = Sheets("Sheet1").Cells(9, Columns.Count).End(xlToLeft).Column 
    lastcol_name_1 = Replace(Cells(1, LastColumn).Address(False, False), "1", "") 

    For i = LastColumn To 1 Step -1 
    lastcol_name_1 = Replace(Cells(1, i).Address(False, False), "1", "") 
    If (lastcol_name_1 = "F" Or lastcol_name_1 = "G" Or lastcol_name_1 = "K") Then 
     If Application.CountA(Columns(i).EntireColumn) = 0 Then 
     Columns(i).Delete Shift:=xlToLeft 
     End If 
    End If 
    Next i 

End Sub