如果标题为"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
答案 0 :(得分:4)
此任务完全没有Scripting.Dictionary。
UsedRange
的标题行Range
对象中的匹配列(通过Application.Union()
)另外,想一个比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
答案 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