EXCEL VBA – 删除列是否存在

我有一个要求,其中,如果存在,我需要删除该特定列。

我想通过列标题find特定的列。

这是我的代码,

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)for循环,查找特定string的标题行的范围。
Pro:简单Con:string必须精确

就像是

 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

你可以简单地去这样

 Dim col As Variant With Sheets("RS_Report") '<--| reference relevant worksheet col = WorksheetFunction.Match("RSD", .Rows(1), 0) '<--| try searching its row 1 for wanted header text If Not IsError(col) Then .Columns(col).Delete '<--| if found then delete its entire column End With