简体   繁体   English

在VBA中,删除除这些特定的列以外的所有列

[英]In VBA, delete all columns except these specific one

I have numbers that correspond to columns in Excel: Columns 4, 5, 6, 7, 26, 28. These columns are dynamically changing depending on the worksheet and depend on the above code. 我有与Excel中的列相对应的数字:列4、5、6、7、26、28。这些列根据工作表和以上代码而动态变化。

How can I delete all the columns in the worksheet EXCEPT for these columns? 如何删除工作表中除这些列以外的所有列?

Give this a try: 试试看:

Sub KolumnKiller()
    Dim s As String, i As Long
    s = ",4,5,6,7,26,28,"
    Application.ScreenUpdating = False
        For i = Columns.Count To 1 Step -1
            If InStr(1, s, "," & i & ",") = 0 Then Cells(1, i).EntireColumn.Delete
        Next i
    Application.ScreenUpdating = True
End Sub

Note: 注意:

You can speed this up a bit by starting with something like 1000 rather than Columns.Count if you know that the far right-hand columns are already empty. 您可以从类似1000而不是Columns的开头开始加快速度,如果知道最右边的列已经为空,则可以进行计数

Updated for a silly mistake in my explanation! 更新是因为我的解释中有一个愚蠢的错误!

I prefer not to respond to posts with no sample code in the question (effort in/effort out principle), but in this case there's a really important aspect that you'll need to consider: You have the choice of looping through each worksheet column and checking if it's in your target list or of just looping through your target list (obviously much quicker). 我宁愿不回答问题中没有示例代码的帖子(“努力” /“努力”原则),但是在这种情况下,您需要考虑一个非常重要的方面:您可以选择遍历每个工作表列并检查它是否在目标列表中,或者只是遍历目标列表(显然要快得多)。 The decision rides on one important question: is your columns list sorted? 这个决定取决于一个重要的问题: 您的栏目列表是否已排序?

I know your question shows the columns in order but I wanted to mention it in case there's any chance of the list becoming disordered or if other readers have unsorted columns. 我知道您的问题按顺序显示了各列,但是我想提一下,以防万一列表变得无序或其他读者的列未排序。

The answer given by Gary's Student will work well and his code deals nicely with an out of sequence list (he's an experienced contributor to this site and the Instr solution keeps things nice and concise). Gary的学生给出的答案将很好地工作,并且他的代码可以很好地处理乱序列表(他是该站点的经验丰富的撰稿人, Instr解决方案使事情变得简洁明了)。

However, if you could ensure the list was in order (smallest to largest), or you were prepared to sort the list yourself, then you could have a much quicker solution, as it enables you only to loop through the target list. 但是,如果您可以确保列表按顺序排列(从最小到最大),或者准备好自己对列表进行排序,那么您可以有一个更快的解决方案,因为它仅允许您遍历目标列表。 It's also a matter of preference but I like to manage row and column deletions in one batch, purely from a time perspective. 这也是一个优先事项,但我希望完全从时间角度来管理一批中的行和列删除。 So the code below is a sample of how you might do it: 因此,下面的代码是如何执行此操作的示例:

    Dim ws As Worksheet
    Dim goers As Range
    Dim keepers As Variant
    Dim v As Variant
    Dim thisCol As Long
    Dim lastCol As Long

    'Your list of columns to keep
    keepers = Array(2, 4, 5, 8, 11, 12, 15)


    Set ws = ThisWorkbook.Worksheets("Sheet1")

    'Initialise goer at column 1 or set to nothing if 1 is a keeper
    Set goers = IIf(keepers(0) = 1, Nothing, ws.Columns(1))

    'Loop through the list extending the column range to next keep column
    lastCol = 1
    For Each v In keepers
        thisCol = v
        If thisCol - lastCol > 1 Then
            Set goers = DelCols(ws, goers, lastCol, thisCol)
        End If
        lastCol = thisCol
    Next

    'Extend to end of worksheet
    Set goers = DelCols(ws, goers, lastCol, ws.Columns.Count)

    'Delete the goers
    goers.Delete


End Sub
Private Function DelCols(ws As Worksheet, cols As Range, col1 As Long, col2 As Long) As Range
    'Helper function to deal with Union
    Dim rng As Range

    'Resize the columns from last+1 to this
    Set rng = ws.Columns(col1 + 1).Resize(, col2 - col1)
    If cols Is Nothing Then
        Set cols = rng
    Else
        Set cols = Union(cols, rng)
    End If

    Set DelCols = cols
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM