Excel VBA - 查找匹配的列标题并删除列

时间:2017-11-21 10:46:34

标签: excel vba excel-vba

如果之前已经回答道歉,我无法找到符合我具体案例的任何内容。

我有一张18张工作簿,每张纸的列数可变,从B2开始。有时生成工作表的程序会创建重复的列,因此,我需要一个按钮触发的宏来搜索每个工作表以查找匹配的列标题,然后删除其中一列(整个列,而不仅仅是标题)。

到目前为止,我已经陷入困境,我已经能够从工作表中的任何单元格中删除所有匹配项,这几乎擦除了整个表格。我只需要匹配标题,然后根据它删除整个列。

如果您需要更多信息,请与我们联系,谢谢您的帮助!

到目前为止,代码还在做其他一些事情,所以这需要继续工作。

    Sub RemoveExtras()

Dim MyRange As Range
Dim ws As Worksheet

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

BadCharacters = Array(Chr(10), Chr(13))
wsNumber = Sheets.Count

For Each ws In Worksheets
    With ws
        For Each MyRange In .UsedRange
            If 0 < InStr(MyRange, Chr(10)) Then
             For Each i In BadCharacters
                MyRange = Replace(MyRange, i, vbNullString)
             Next i
            End If
             For t = 1 To wsNumber
              Columns(t).RemoveDuplicates Columns:=Array(1), Header:=xlYes
              Next t
        Next MyRange
    End With
Next ws

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub

2 个答案:

答案 0 :(得分:1)

看看这有助于你

Sub test()

Dim book As Workbook, sheet As Worksheet, text As String

For Each sheet In Worksheets


    Set MR = Range("B2:Z2") 'change Z2 as per your requirement
    For Each cell In MR
        Set BR = Range("B2:Z2") 'change Z2 as per your requirement
        For Each cell2 In BR
            If cell.Value = cell2.Value Then cell.EntireColumn.Delete
        Next
    Next

Next sheet


End Sub

答案 1 :(得分:1)

词典非常适合处理独特的价值观:

DF <- structure(list(Dev_Func = structure(c(1L, 1L, 2L, 2L, 1L), .Label = c("agn", 
"ttt"), class = "factor")), .Names = "Dev_Func", row.names = c(NA, 
-5L), class = "data.frame")

此处您不会比较工作表中的每对列标题。此外,这会比较所有工作表中的标题,而不仅仅是单个工作表中的重复项。