如果列标题包含某个字符串,则删除列

时间:2016-03-20 13:34:33

标签: excel vba excel-vba

如果标题为"Column 1""Column 2"等,我想删除列。

我正在尝试修改以下代码,以便将“Column x”添加到Dictionary中,然后删除列,如果它包含单词 - 我做错了什么?

Sub Macro2()
    Set Dict_Col = CreateObject("Scripting.Dictionary")
    ArrayCol = Sheets("Sheet2").Range(Cells(1, 1).Address, Cells(Rows.Count).End(xlUp).Address)

    ' I'm not sure what to add as a wildcard to the x?
    Dict_Col.Add UCase(Trim("Column x")), 1 

    For i = Cells(1, Columns.Count).End(xlToLeft).Column To 1 Step -1
        If Dict_Col.Exists(UCase(Trim(Cells(1, i).Value))) Then
            Cells(1, i).EntireColumn.Delete
        End If
    Next i
End Sub

3 个答案:

答案 0 :(得分:4)

此任务完全没有Scripting.Dictionary。

  1. 浏览循环中UsedRange的标题行
  2. 检查列名是否具有正确的格式
  3. 收集Range对象中的匹配列(通过Application.Union()
  4. 最后一步删除该Range对象。
  5. 另外,想一个比Macro2更好的名字。

    Sub Macro2()
        Dim header As Range, toRemove As Range
        Dim parts As Variant
    
        For Each header In Sheets("Sheet2").UsedRange.Rows(1).Cells
            parts = Split(header.Value, " ")
            If UBound(parts) = 1 Then
                If parts(0) = "Column" And IsNumeric(parts(1)) Then
                    If toRemove Is Nothing Then
                        Set toRemove = header.EntireColumn
                    Else
                        Set toRemove = Application.Union(toRemove, header.EntireColumn)
                    End If
                End If
            End If
        Next header
    
        If toRemove Is Nothing Then
            MsgBox "Nothing found."
        Else
            toRemove.Delete
        End If
    End Sub
    

    (未经测试,目前我没有Excel方便,但总的想法应该很明显。)

答案 1 :(得分:0)

替代解决方案

Option Explicit

Sub delcolumns()

With ThisWorkbook.Worksheets("Sheet2")
    .Rows(1).Insert
    .Rows(2).SpecialCells(xlCellTypeConstants, xlTextValues).Offset(-1).FormulaR1C1 = "=IF( COUNTIF(R[+1]C,""Column ?"") + COUNTIF(R[+1]C,""Column ??"") + COUNTIF(R[+1]C,""Column ???"") >0 ,1,"""")"
    .Rows(1).SpecialCells(xlCellTypeFormulas).Value = .SpecialCells(xlCellTypeFormulas).Value
    .Rows(1).SpecialCells(xlCellTypeConstants, xlNumbers).EntireColumn.Delete
    .Rows(1).Delete
End With

End Sub
  • 没有迭代
  • 使用辅助行(在end sub之前插入和删除)
  • 假设“Column”之后的数字最多可以是3位数。如果不只是改编公式

答案 2 :(得分:-1)

Sub Macro2()
    Set Dict_Col = CreateObject("Scripting.Dictionary")
    ArrayCol = Sheets("Sheet2").Range(Cells(1, 1).Address, Cells(Rows.Count).End(xlUp).Address)
Dict_Col.Add UCase(Trim("Column")), 1
For x = 2 To 100

    Dict_Col.Add UCase(Trim("Column" & x)), x
   Next x


    For i = Cells(1, Columns.Count).End(xlToLeft).Column To 1 Step -1
        If Dict_Col.Exists(UCase(Trim(Cells(1, i).Value))) Then
            Cells(1, i).EntireColumn.Delete
        End If
    Next i
End Sub