2017-04-06 54 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