【问题标题】:In VBA, delete all columns except these specific one在 VBA 中,删除除这些特定列之外的所有列
【发布时间】:2016-09-25 20:02:06
【问题描述】:

我有与 Excel 中的列相对应的数字: 第 4、5、6、7、26、28 列。这些列会根据工作表动态变化,并取决于上述代码。

如何删除工作表中除这些列之外的所有列?

【问题讨论】:

    标签: excel vba multiple-columns


    【解决方案1】:

    试试这个:

    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
    

    注意:

    如果您知道最右侧的列已经是空的,则可以从 1000 之类的东西开始而不是 Columns.Count 来加快速度。

    【讨论】:

      【解决方案2】:

      更新了我的解释中的一个愚蠢的错误!

      我不想回复问题中没有示例代码的帖子(努力输入/努力输出原则),但在这种情况下,您需要考虑一个非常重要的方面:您可以选择循环每个工作表列并检查它是否在您的目标列表中或只是循环通过您的目标列表(显然要快得多)。该决定取决于一个重要问题:您的列列表是否已排序?

      我知道您的问题按顺序显示了列,但我想提一下,以防列表变得混乱或其他读者的列未排序。

      Gary 的 Student 给出的答案会很好地工作,他的代码可以很好地处理乱序列表(他是该站点的一位经验丰富的贡献者,Instr 解决方案使事情变得简洁明了)。

      但是,如果您可以确保列表是有序的(从小到大),或者您准备好自己对列表进行排序,那么您可以有一个更快的解决方案,因为它只允许您遍历目标列表.这也是一个偏好问题,但我喜欢一次性管理行和列的删除,纯粹从时间的角度来看。所以下面的代码是你可以如何做的一个示例:

          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
      

      【讨论】:

        猜你喜欢
        • 2018-02-01
        • 2020-07-22
        • 2018-11-23
        • 2015-03-27
        • 1970-01-01
        • 2017-09-24
        • 2020-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多