2017-04-06 66 views
0

我有一個需求,其中,如果存在,我需要刪除該特定列。EXCEL VBA - 刪除列是否存在

我想通過列標題找到特定列。

這是我的代碼,

If sColumnName = (WorksheetFunction.Match("RSD", Sheets("RS_Report").Rows(1), 0)) And sColumnName = True Then 

DDC= WorksheetFunction.Match("RSD", Sheets("RS_Report").Rows(1), 0) 

DFC= GetColumnLetter(DDC) 

Range(DFC& 1 & ":" & DFC& lastrow).Select 

Selection.Delete Shift:=xlUp 

的GetColumnLetter和LASTROW是我的用戶定義的函數,它們返回正確的值。我不確定如何檢查列是否存在。請幫助我。分享你的意見。

回答

1

有三種方法可以做到這一點。

1)for循環,查找特定字符串的標題行的範圍。
臨:它很容易 缺點:該字符串必須是準確的

Dim string as yourString 
Dim lColumn As Long 
lColumn = ws.UsedRange.Columns.Count 
yourString = whatever 
for x = 1 to lcolumn 
    if range(cells(1, 1), Cells(1, x)).Value = yourString 
    Columns(x).EntireColumn.Delete 
    End If 
next 

2)使用Range.Find方法,你可以瞭解這裏https://msdn.microsoft.com/en-us/library/office/ff839746.aspx

這裏是一個簡短粗糙的例子,你可以用作參考:

Sub Header_Format() 
Dim rLastCell As Range 
Set rLastCell = UpdateSheet.Cells.Find(What:="*", After:=UpdateSheet.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _ 
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False) 
    With UpdateSheet.Range(Cells(4, 1), Cells(4, rLastCell.Column)) 
     .Copy MasterSheet.Cells(1, 1) 
     .Copy RemovalSheet.Cells(1, 1) 
    End With 
End Sub 

3)最後有使用匹配方法,已經有人發言了。

https://msdn.microsoft.com/en-us/library/office/ff835873.aspx

2

,你可以簡單地去這樣

+1

尼斯,對於另一個;) –

+1

@ShaiRado,謝謝。不過你爬得很快! – user3598756

+1

@VBA_Begineer,出於好奇你能告訴我爲什麼你選擇Jaberwocky的解決方案?謝謝 – user3598756