2014-01-28 51 views
0

我有幾百個excel中的列,我不需要。我有一個我想保留的範圍。刪除所有列,但不包括一列excel VBA

在分鐘我就要

Sub DeleteClms() 
    Range("A:G,L:O").Delete 
End Sub 

反正有使這是一個相對的,在其他語言中,我只想把=! 我試過把<>放進去,但我不知道在哪裏/如何將它放入我的代碼中?

感謝

+0

hmmmm,不知道你可以使用<>,如果我是你情我願剛剛錄製宏,並選擇我想要刪除的所有列。然後進去整理一下。 – SeekingAlpha

+0

否 - 在VBA中沒有相應的直接方法。最接近的會複製你想要的範圍,而不是刪除你不想要的範圍。 – brettdj

回答

0

沒有爲我所知道的列對稱的差異沒有Excel或VBA函數。

這裏是一個快速VBA功能去那裏。用法是DeleteAllBut Range("A:C,H:Q")

Sub DeleteAllBut(rngToKeep As Range) 
    Dim ws As Worksheet 
    Dim rngToDelete As Range 
    Dim rngColi As Range 

    'Number of columns used in worksheet 
    Set ws = rngToKeep.Parent 
    iCols = ws.UsedRange.Columns.Count 

    FirstOne = True 
    For i = 1 To iCols 
     Set rngColi = Range("A:A").Offset(0, i - 1) 
     If Intersect(rngToKeep, rngColi) Is Nothing Then 
      If FirstOne Then 
       Set rngToDelete = rngColi 
       FirstOne = False 
      Else 
       Set rngToDelete = Union(rngColi, rngToDelete) 
      End If 
     End If 
    Next i 

    Debug.Print rngToDelete.Address & " was deleted from " & ws.Name 
    rngToDelete.Delete 


End Sub